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.I'd like to reduce the complexity of my code.import java.math.BigInteger;import java.util.Scanner;public class Solution {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int testCases = sc.nextInt();        for (int i = 0; i < testCases; i++) {            BigInteger input = sc.nextBigInteger();            System.out.println(calculate(input));        }    }    public static BigInteger calculate(BigInteger input) {        BigInteger fib1 = new BigInteger(0);        BigInteger fib2 = new BigInteger(1);         BigInteger sum = new BigInteger(0);        BigInteger fib = new BigInteger(0);        while (input.compareTo(fib)>0) {            if (fib.doubleValue() % 2 == 0)                sum = sum.add(fib);            fib = fib1.add(fib2);            fib1 = fib2;            fib2 = fib;        }        return sum;    }}
Project Euler #2 Efficiency
java;programming challenge;fibonacci sequence
The test if (fib.doubleValue() % 2 == 0)does not produce the correct result for numbers with more than 17 digits, becausethat exceeds the precision of a double. Actually it returns true for 8944394323791464 and all subsequent Fibonacci numbers.That is not relevant for the concrete problem here (see below), but if you want to work with BigInteger then you should replace this withif (fib.remainder(bigTwo).equals(BigInteger.ZERO))where bigTwo is defined asBigInteger bigTwo = new BigInteger(2);Project Euler Problem #2asks for the sum of all even-valued Fibonacci values not exceeding 4 million,so using BigInteger is not really necessary. All numbers fit into the rangeof int, and the above test simplifies toif (fib % 2 == 0)(I also planned to tell that using int instead of BigInteger makes theprogram more efficient, but it turned out that the difference in runningtime is not significant.)