blake41/eulers — comment on commit 01727ab1d2d22ce8b486ed5c200a45b448e8afe8
File:  line 0
By raywu:

For Problem 2: Check out Ian's https://github.com/igrabes/Euler-Project/blob/master/euler2.rb

We noticed that his solution takes a long time, too, because the algorithm loops through each prior fib(1..n) each time it's called. For instance for fib(4), it runs fib(1), then fib(2), fib(3) to get to fib(4). And his line 5 fib(n-1) + fib(n-2) really means the algorithm runs fib(n) twice before it gets the sum.

Yours is getting the last two elements in the vals array. The parallel I see is that the algorithm has to run through 34 times before it reaches 4E6; each time getting the sum of last two elements in vals; so it might take about the same time as Ian's.

One way to get around printing 'sum' each time it loops through line 11 is to do this in a block and print only the 'last' sum:

line 11: yield sum # instead of printing the sum each loop
line 12: end
line 13
line 14: fibs = []
line 15: fib(4E6) { |f| fibs << f } # => array of fibonacci numbers' sum
line 16: print fibs.last # => should give you the last sum, which is the answer