I'd like to reduce the complexity of my code.
Problem :
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
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.
My Solution : 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;
}
}