Project Euler #2: Even Fibonacci numbers

Question

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.

Answer  : 4613732

Hacker Rank Question

Solution


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int a0 = 0; a0 < t; a0++){
            long n = in.nextLong();
            long first= 1;
            long second= 2;
            long sum= second;
            for(long i=3; second<n; i++)
            {
                long temp= second;
                second= second + first;
                first= temp;
                if(second % 2 == 0  &&  second < n)
                    sum += second;
            }
            System.out.println(sum);
        }
    }
}

Comments

Popular Posts