# Finding the sum of even valued terms in Fibonacci sequence

## Question:

``````#!/usr/bin/python2

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

odd, even = 0,1
total = 0
while True:
odd = odd + even  #Odd
even = odd + even     #Even
if even < 4000000:
total += even
else:
break
print total
``````

My algo:

1. If I take first 2 numbers as 0, 1; the number that I find first in while loop will be an odd number and first of Fibonacci series.
2. This way I calculate the even number and each time add the value of even to total.
3. If value of `even` is greater than 4e6, I break from the infinite loop.

I have tried so much but my answer is always wrong. Googling says the answer should be `4613732` but I always seem to get `5702886`

Basically what you’re doing here is adding every second element of the fibonacci sequence while the question asks to only sum the even elements.

What you should do instead is just iterate over all the fibonacci values below 4000000 and do a `if value % 2 == 0: total += value`. The `%` is the remainder on division operator, if the remainder when dividing by 2 equals 0 then the number is even.

E.g.:

``````prev, cur = 0, 1
total = 0
while True:
prev, cur = cur, prev + cur
if cur >= 4000000:
break
if cur % 2 == 0:
total += cur
print(total)
``````

it should be:

``````odd, even = 1,0
``````

Also, every third numer is even (even + odd + odd = even).

Your code includes every other term, not the even-valued ones. To see what’s going on, `print even` just before `total += even` – you’ll see odd numbers. What you need to do instead is check the number you’re adding to the total for evenness with the modulo operator:

``````total = 0
x, y = 0, 1
while y < 4000000:
x, y = y, x + y
if x % 2:
continue
total += x

print total
``````

If you add every second value of the fibonacci sequence you’ll get the next fibonacci value after the last added value. For example:

``````f(0) + f(2) + f(4) = f(5)
0 + 1 + 3 + 8 = 13
``````

But your code currently does not add the first even value `1`.

Other answers are correct but note that to just add all even numbers in an array, just do
myarray=[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

``````sum(map(lambda k:k if k%2 else 0, myarray))
``````

or

``````sum([k if k%2 else 0 for k in [1,2,3,4,5]])
``````

Every 3rd item in the Fibonnaci sequence is even. So, you could have this:

``````prev, cur = 0, 1
count = 1
total = 0
while True:
prev, cur = cur, prev + cur
count = count + 1
if cur >= 4000000:
break
if count % 3 == 0:
total += cur
print(total)
``````

or this (changing your code as little as possible):

``````even, odd = 0,1                       # this line was corrected
total = 0
while True:
secondOdd = even + odd                   # this line was changed
even = odd + secondOdd     #Even         # this line was changed
if even < 4000000:
total += even
odd = secondOdd + even               # this line was added
else:
break
print total
``````

Another way would be (by the use of some simple math) to check that the sum of `a2+a5+a8+a11+...+a(3N+2)` (the sum of even Fibonacci values) is equal to `(a(3N+4)-1)/2`. So, if you can calculate directly that number, there is no need to calculate all the previous Fibonacci numbers.

``````def fibonacci_iter(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b

print sum(a for a in fibonacci_iter(4e6) if not (a & 1))
``````

not sure if your question is already answered or you’ve found a solution, but here’s what you’re doing wrong. The problem asks you to find even-valued terms, which means that you’ll need to find every value in the fibonacci sequence which can be divided by 2 without a remainder. The problem does not ask you to find every even-indexed value. Here’s the solution to your problem then, which gives a correct answer:

``````i = 1
total = 0
t = fib(i)
while t <= 4000000:
t = fib(i)
if t % 2 == 0:
total += t
i += 1
print total
``````

Basically you loop through every each value in fibonacci sequence, checking if value is even by using ‘mod’ (% operator) to get remainder, and then if it’s even you add it to sum.

Here is simple solution in C:

``````#include <stdio.h>
#include <stdlib.h>

int main()
{
int i=1,j=1,sum=0;
while(i<4000000)
{
i=i+j;
j=i-j;
if(i%2==0)
sum+=i;
}
printf("Sum is: %d",sum);

}
``````

problem in your code basicly related with looping style and checking condition timing. with below algorithm coded in java you can find (second + first) < 4000000 condition check and it brings you correct ( which less than 4000000) result, have a nice coding…

``````   int first = 0, second = 1, pivot = 0;

do {

if ((second + first) < 4000000) { // this is the point which makes your solution correct
pivot = second + first;
first = second;
second = pivot;
System.out.println(pivot);
} else {
break;
}

} while (true);
``````

Here is how I was able to solve this using native javascript.

``````var sum = 0,
x = 1,
y = 2,
z = 0;
while (z < 4000000) {
if (y%2==0){
sum +=y;
}
z = x + y;
x = y;
y = z;
} console.log(sum);
``````

This is the python implementation and works perfectly.

``````from math import pow
sum=0
summation=0
first,second=1,2
summation+=second
print first,second,
while sum < 4*math.pow(10,6):
sum=first+second
first=second
second=sum
#i+=1
if sum > 4*math.pow(10,6):
break
elif sum%2==0:
summation+=sum
print "The final summation is %d" %(summation)
``````

I did it differently.

``````def fibLessThan(lim):

#################
# Initial Setup #
#################
fibArray=[1, 1, 2]
i=3

#####################
# While loop begins #
#####################
while True:
tempNum = fibArray[i-2]+fibArray[i-1]
if tempNum <= lim:
fibArray.append(tempNum)
i += 1
else:
break

print fibArray
return fibArray

limit =  4000000
fibList = fibLessThan(limit)

#############
# summation #
#############
evenNum = [x for x in fibList if x%2==0]
evenSum = sum(evenNum)
print "evensum=", evenSum
``````

You just misunderstood with the even sequence and even value.

Example: 1, 2, 3, 5, 8, 13, 21

In the above sequence we need to pick 1, 3, 5, 13, 21 and not 2, 5, 13.

Here is the solution fro JAVA

`````` public static void main(String[] args) {
int sum = 2;    // Starts with 1, 2: So 2 is added
int n1=1;
int n2=2;
int n=0;

while(n<4000000){
n=n1+n2;
n1=n2;
n2=n;
if(n%2==0){
sum=sum+n;
}
}
System.out.println("Sum: "+sum);
}
``````

Output is,

Sum: 4613732

Here is my Python code:

``````even_sum = 0
x = [1, 1] # Fibonacci sequence starts with 1,1...

while (x [-2] + x [-1]) < 4000000: # Check if the coming number is smaller than 4 million
if (x [-2] + x [-1]) % 2 == 0: # Check if the number is even
even_sum += (x [-2] + x [-1])
x.append (x [-2] + x [-1]) # Compose the Fibonacci sequence
print (even_sum)
``````
``````def fibLessThan(lim):
a ,b = 1,2
total = 0
while b<lim:
if b%2 ==0:
total+=b
a,b = b,a+b
``````

I tried this exactly working answer. Most of us are adding number after fib formula where we are missing 2. With my code I am adding 2 first then fib formula. This is what exact answer for the Euler problem.

code in python3:

``````sum = 2
a = 1
b = 2
c = 0

while c <= 4000000:
c = a + b
if c%2 == 0:
sum += c

a,b = b,c

print(sum)
``````

output >>> 4613732

Although it’s hard to believe that a question with 17 answers needs yet another, nearly all previous answers have problems in my view: first, they use the modulus operator (%) aka division to solve an addition problem; second, they calculate all the numbers in the sequence and toss the odd ones; finally, many of them look like C programs, using little of Python’s advantages.

Since we know that every third number of the Fibonacci sequence is even, we can generate every third number starting from 2 and sum the result:

``````def generate_even_fibonacci(limit):
previous, current = 0, 2

while current < limit:
yield current

previous, current = current, current * 4 + previous

print(sum(generate_even_fibonacci(4_000_000)))
``````

OUTPUT

``````> python3 test.py
4613732
>
``````

This is the second problem in the Project Euler series.

It is proven that every third Fibonacci number is even (originally the zero was not part of the series). So I start with a, b, c being 0,1,1 and the sum will be every recurring first element in my iteration.
The values of my variables will be updated with each being the sum of the preceding two:
`a = b + c`, `b = c + a` , `c = a + b`.

The variable `a` will be always even. In this way I can avoid the check for parity.

In code:

``````
def euler2():
a, b, c, sum = 0, 1, 1, 0
while True:
print(a, b, c)
a, b, c = (b + c), (2 * c + b), (2 * b + 3 * c)
if a >= 4_000_000:
break
sum += a
return sum

print(euler2())

``````

So much code for such a simple series. It can be easily shown that f(i+3) = f(i-3) + 4*f(i) so you can simply start from 0,2 which are f(0),f(3) and progress directly through the even values striding by 3 as you would for the normal series:

``````s,a,b = 0,0,2
while a <= 4000000: s,a,b = s+a,b,a+4*b
print(s)
``````

I solved it this way:

``````list=[1, 2]
total =2
while total< 4000000:
list.append(list[-1]+list[-2])
if list[-1] % 2 ==0:
total += list[-1]
print(total)
``````
``````        long sum = 2;
int start = 1;
int second = 2;
int newValue = 0;
do{
newValue = start + second;
if (newValue % 2 == 0) {
sum += newValue;
}
start = second;
second = newValue;
} while (newValue < 4000000);
System.out.println("Finding the totoal sum of :" + (sum));`enter code here`
``````

The first mistake was you messed the Fibonacci sequence and started with 0 and 1 instead of 1 and 2. The sum should therefore be initialized to 2

``````#!/usr/bin/python2
firstNum, lastNum = 1, 2
n = 0
sum = 2  # Initialize sum to 2 since 2 is already even
maxRange = input("Enter the final number")
max = int(maxRange)

while n < max:
n = firstNum + lastNum
firstNum = lastNum
lastNum = n

if n % 2 == 0:
sum = sum + n

print(sum)
``````

# It works completely fine:)

``````n = int(input())
f = [0, 1]
for i in range(2,n+1):
f.append(f[i-1]+f[i-2])
sum = 0
for i in f:
if i>n:
break
elif i % 2 == 0:
sum += i
print(sum)
``````

There are many great answers here. Nobody’s posted a recursive solution so here’s one of those in C

``````#include <stdio.h>

int filt(int n){
return ( n % 2 == 0);
}

int fib_func(int n0, int n1, int acc){
if (n0 + n1 > 4000000)
return acc;
else
return fib_func(n1, n0+n1, acc + filt(n0+n1)*(n0+n1));
}

int main(int argc, char* argv){
printf("%dn", fib_func(0,1,0));
return 0;
}
``````
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.