Skip to content

Latest commit

 

History

History
38 lines (35 loc) · 1.06 KB

Even Fibonacci Numbers.md

File metadata and controls

38 lines (35 loc) · 1.06 KB

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

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the limit: ");
        int n = sc.nextInt();
        int a = 1;
        int b = 2;
        int sum = 0;
        int total = 0;
        for (int i = 0; i < n; i++) {
            if (sum < (n - a)) {
                int temp = b;
                sum = a + b;
                if (sum % 2 == 0) {
                    total += sum;
                }
                a = temp;
                b = sum;
            }
        }
        System.out.println("Sum of the even valued terms in Fibonacci Sequence is : " + total + 2);
        sc.close();
    }
}