Friday, September 23, 2011

Project Euler - Problem Two

Recursion is so much fun. It's not the easiest thing I've ever tried to wrap my mind around, but it's fun.

Okay, so here is the solution to Project Euler's second problem.

The problem is this:
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.

So, you're going to need to figure out what this means.
int fib(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    else
        return fib(n - 1) + fib(n - 2);


This is the code to find the fib of a number. If you put ten in, you'll get 89. Now, simply putting fib() of four million won't work. We want the sum of the even-valued terms.  In other words, we need something else to make it happen.

Personally, I used a do/while loop with an if statement inside of it.

You can see what I did here. The actual solution is 4613732.


No comments:

Post a Comment