Skip to content

Instantly share code, notes, and snippets.

@Davidslv
Created October 8, 2013 23:10
Show Gist options
  • Save Davidslv/6893396 to your computer and use it in GitHub Desktop.
Save Davidslv/6893396 to your computer and use it in GitHub Desktop.
factorial
# This are examples of how to implement a factorial in Ruby
def ft(n)
return 1 if n <= 1
n.downto(1).inject(:*)
end
def factorial(n)
return 1 if n <= 1
n * factorial(n - 1)
end
@Davidslv
Copy link
Author

Davidslv commented Oct 8, 2013

Difference

>> Benchmark.bmbm{|x| x.report { ft(10001) } }
Rehearsal ------------------------------------
   0.380000   0.010000   0.390000 (  0.390454)
--------------------------- total: 0.390000sec

       user     system      total        real
   0.370000   0.020000   0.390000 (  0.385317)
=> [#<Benchmark::Tms:0x112cdb0a0 @total=0.390000000000004, @cstime=0.0, @cutime=0.0, @label="", @stime=0.0199999999999996, @real=0.385316848754883, @utime=0.370000000000005>]


>> Benchmark.bmbm{|x| x.report { factorial(10001) } }
Rehearsal ------------------------------------
 SystemStackError: stack level too deep
    from (irb):99:in `factorial'
    from (irb):100:in `factorial'
    from (irb):121
    from /Users/davidslv/.rbenv/versions/ree-1.8.7-2011.03/lib/ruby/1.8/benchmark.rb:293:in `measure'
    from /Users/davidslv/.rbenv/versions/ree-1.8.7-2011.03/lib/ruby/1.8/benchmark.rb:261:in `bmbm'
    from /Users/davidslv/.rbenv/versions/ree-1.8.7-2011.03/lib/ruby/1.8/benchmark.rb:259:in `each'
    from /Users/davidslv/.rbenv/versions/ree-1.8.7-2011.03/lib/ruby/1.8/benchmark.rb:259:in `bmbm'
    from (irb):121

@Davidslv
Copy link
Author

Davidslv commented Oct 8, 2013

#include <stdio.h>

int main() {
  int c, n;
  long double fact = 1;

  printf("=>");
  scanf("%d", &n);

  for (c=1; c <= n; c++) {
    fact = fact * c;
  }

  printf("%Le\n", fact); /* this is still not the correct output */
  return 0;
}
./factorial
=>10001
inf

@Davidslv
Copy link
Author

Davidslv commented Feb 5, 2014

Read the one made with erlang here: https://gist.github.com/Davidslv/8832054

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment