Skip to main content
  1. Problem Solving Solutions/

Even Fibonacci Numbers - HackerRank - Project Euler #2

·1 min
Project-Euler
Mayukh Datta
Author
Mayukh Datta

Read the problem statement here:

Project Euler:  https://projecteuler.net/problem=2

HackerRank:  https://www.hackerrank.com/contests/projecteuler/challenges/euler002/problem

Java code:

import java.util.*; class Solution{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t– > 0){ long n = in.nextLong(); System.out.println(SumEvenFibo(n)); } in.close(); } static long SumEvenFibo(long n){ long first = 1, second = 2, next = 3, sum = 2;

    while(second < n){
        if(next % 2 == 0){
            sum += next;
        }
        next = first + second;
        first = second;
        second = next;
    }
    return sum;
}

}

It has a \(O(n)\) time complexity.

This problem can be solved in \(O(1)\) time. Read the post here.