Project Euler #2: Even Fibonacci numbers | Hackerrank | Project Euler

 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,3,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.

Constraints

1<=T<=10^5
10<=N<=4*10^16

Output Format

Print the required answer for each test case.

Sample Input 0

2
10
100

Sample Output 0

10
44

Explanation 0

For N=10, we have {2,8}, sum is 10.
For N=100, we have {2,8,34}, sum is 44.


Solution:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int t; 
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0++){
        long n,sum=2,p1 = 1p2 = 2, fib = 0
        scanf("%ld",&n);
         fib= p1 + p2;
        while (fib <= n) {
         if(fib%2==0)
            sum=sum+fib;
         p1 = p2;
         p2 = fib;
         fib = p1 + p2;
    }
        printf("%ld\n",sum);
    }
    return 0;
}


You can also run it on an online IDE: 


Your feedback are always welcome! If you have any doubt you can contact me or leave a comment!  Happy Coding !! Cheers!!!

No comments:

Post a Comment

Super Market Problem | TCS Code Vita 2023 - Zone 1 | Super Market TCS Code Vita 2023 Solution | Code Vita 2023 | Code Vita 2023 season 11 solution

 Problem Description: In a Super market we will find many variations of the same product. In the same way we can find many types of rice bag...