From: "W. James" Date: 2009-12-19T10:20:14+09:00 Subject: Re: Question about sum of fibonacci sequene [PROJECT EULER] Panagiotis Atmatzidis wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Dear Sirs, > > Just to improve my programming skills and experience I found amusing > solving problems like the ones posed by project Euler. Doing so, > using Ruby is a joy, compared to Objective-C that I've used for the > same purpose in the past. > > I'm stuck in the second problem though. Here is the issue: > > Each new term in the Fibonacci sequence is generated by adding the > previous two terms. By starting with 1 and 2, the first 10 terms will > be: > > 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... > > Find the sum of all the even-valued terms in the sequence which do > not exceed four million. > > I think that my code solves it. Works when I test it to smaller > fractions, can someone reply if there's something wrong with this > snippet: - --------------- # fibonacci > > a = 1 > b = 0 > sum = 0 > while a <= 4000000 > # get the old value of "a" > c = a + b > #puts c > if (c % 2 != 0) > sum = sum + c > end > b = a > a = c > end > > puts sum > - --------------- > > Well my result is: 10316618 . I know that the original Fibonacci > sequence will have a (+1) in the beginning of the loop, but > (probably) for the sake of convenience is ignored. The system however > returns a "false error" in both 10316618 and 10316618 + 1. > > Thanks in advanced & best regards sum = 0 a,b = 1,1 while a <= 4_000_000 sum += a if a.even? a,b = b,a+b end p sum --