Hey guys,
Hope you all are doing great. I am back with another problem of Project Euler

Project Euler #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 N, find the sum of the even-valued terms.
Input Format
First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.
Output Format
Print the required answer for each test case.
Constraints
1T105
10N4×1016
Sample Input
2
10
100
Sample Output
10
44
Algorithm:
Fibonacci Series is one of the most fundamental series in programming world.

To proceed, you just need to add 2 numbers just prior to your current number. Starting with 1 and 1 it becomes:

  1. 1
  2. 1
  3. 1+1 = 2
  4. 1+2 = 3
  5. 2+3 = 5
  6. and so on....
Here python comes to our rescue to code it efficiently. As we need only even numbers, will have a condition as num%2 == 2

Now for the main part, taking a and b as the cursors to our program,
Initialize them with a=1, b=1
Then as in Python you can assign INLINE a number of variables so our mail condition becomes
a , b = a , a+b
In this way we are handling both previous numbers and calculating the nest number concurrently.


And Presto!! Its Done!!

Just we need to convert that into a code, which is easy ion Python, Check the below code:
 Program:


t=input();
while (t>0):
    t-=1
    n=input()
    a, b = 1, 1;
    total = 0;
    while a <= n:
        if a % 2 == 0:
            total += a
        a, b = b, a+b  # the real formula for Fibonacci sequence
    print total;
2

View comments

Loading