Monday, October 31, 2011

Solution to ProjectEuler Problem2 - Fibonacci Series till 4 million and sum of even numbers

projecteuler.net problem 2

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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Answer: 4613732

Solution:

#!/usr/bin/perl -w
use strict;
my ($sum, $first, $second, $evensum);
$first=1;
$second=2;
$evensum=2;
print "Fibonacci sequence \n";
print "$first $second";
fib($first,$second);


sub fib
{
        my ($num1, $num2)=@_;
        #Limiting fibonacce sequence to 4000000
        if ($num2 <= 3500000 )
        {
                $sum=$num1+$num2;
                print " $sum";
                if ( ($sum%2) == 0 ) {
                        $evensum+=$sum;
                }
                fib($num2, $sum);
        }else {
                print "\nEven Sum = $evensum \n";
                exit (0);
        }
}


Output:
Fibonacci sequence till 4000000
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578
Even Sum = 4613732

No comments: