asda
Ruby
code posted
by
asda
created at 09 Oct 22:53
Edit
|
Back
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
require 'benchmark' def fib1(n) #return n<2 ? n : fib1(n-1)+fib1(n-2) if n<2 then return n else return fib1(n-1)+fib1(n-2) end end def fib2(n) i=1 j=0 n.times { j=i+j i=j-i } return j end def fib3(n) i=1 j=0 k=0 h=1 while n>0 if n%2!=0 t=j*h j=i*h+j*k+t i=i*k+t end t=h*h h=2*k*h+t k=k*k+t n/=2 end return j end Benchmark.bm (10){ |x| x.report("fib1time: ") { fib1(35)}} puts Benchmark.bm (10){ |x| x.report("fib1time: ") { fib1(35)}} puts Benchmark.bm (10){ |x| x.report("fib1time: ") { fib1(35)}} puts Benchmark.bm (10){ |y| y.report("fib2time: ") { fib2(208000)}} puts Benchmark.bm (10){ |z| z.report("fib3time: ") { fib3(4000000)}} |
747 Bytes in 3 ms with coderay