P.E.2: Even Fibonacci numbers

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.


The answer is 4613732.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

3 solutions

Swapnil Bhargava
Sep 21, 2014

Here's my C++ code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream>
#include<cstdio>
#define limit 4000000
using namespace std;
int main()
{
    long long int a=1,b=2,c;
    double sum=2;
    while(1)
    {
        c=a+b;
        if(c>limit)
            break;
        if(c%2==0)
            sum+=(double)c;
        a=b;
        b=c;
    }
    printf("%.0lf",sum);
    return 0;
}

Brock Brown
Jan 4, 2015

0.000314 second evaluation time using Python:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
memo = {1:1,2:1}
def fib(n):
    if n in memo:
        return memo[n]
    memo[n] = fib(n - 1) + fib(n - 2)
    return memo[n]
total = 0
i = 1
while fib(i) <= 4000000:
    if fib(i) % 2 == 0:
        total += fib(i)
    i += 1
print "Answer:", total

Arvind Srinivasan
Sep 18, 2014

My Python code goes as follows:

"""
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.
"""
sum = 0
x, y = 0, 1
while y < 4000000:
    x, y = y, x + y
    if x % 2:
        continue
    sum = sum + x

print "The sum of the even valued terms in a fibonacci sequence less than 4 million is:"
print sum

Hope this helps!

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...