On Dec 18, 2009, at 2:50 PM, 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)

Note: c % 2 != 0 is only true for ODD values of c and you wanted EVEN  
values.  Change the 4000000 to be 10 and you ought to see the  
difference: 1, 2, 3, 5, 8 means 1+3+5=9 for odds and 2+8=10 for evens

>  sum = sum + c

you could do:
puts [ c, sum ].inspect
to see the c's that are being added

> 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.

Your sequence will be 1, 1, 2, 3, 5, 8, 13, ...
If you initialize b=1, then you should get 1, 2, 3, 5, 8, 13, ...

>
> Thanks in advanced & best regards
>
> Panagiotis (atmosx) Atmatzidis
>
> email:	atma / convalesco.org
> URL:	http://www.convalesco.org


Once you get the right answer, you should think about why the value of  
your first guess is off to the degree that it is.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com