Wednesday, September 9, 2009

Euler Problem 2

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.

Powershell Solution:

  1. $n1 = 1 
  2. $n2 = 1 
  3. $sum = 0 
  4. while(($n1+$n2) -lt 4e+6) 
  5.     if($n2 -gt $n1
  6.     { 
  7.         $n1=$n1+$n2 
  8.         if($n1%2 -eq 0) 
  9.         { 
  10.             $sum = $sum + $n1 
  11.         } 
  12.     } 
  13.     else 
  14.     { 
  15.         $n2=$n1+$n2 
  16.         if($n2%2 -eq 0) 
  17.         { 
  18.             $sum = $sum + $n2 
  19.         } 
  20.     } 
  21. }  
  22. $sum 

$sum = 4613732

The above solution doesn’t look that elegant though…
I think it can still be optimized… but anyway, I’ll try again if I have the time…

2 comments:

harbyherbman said...
This comment has been removed by a blog administrator.
Paul Lorett Amazona said...

Sorry for removing the comment.
But, kindly post something that is related. Irrelevant advertisement seems inappropriate. Thank you for your kind consideration.