I am trying to solve Project Euler problem 2 in Java:
public class Euler2 {
public static long GenerateFibonacci(int term) {
long sum = 0;
long fib = 0;
long f1 = 0;
long f2 = 1;
if (term <=1) return term;
for (int i = 1; i <= term; i++) {
fib = f1 + f2;
f1 = f2;
f2 = fib;
if(fib %2 ==0)
sum += fib;
}
return sum;
}
/**
* @param args
*/
public static void main(String[] args) {
int n = 100;
long result = GenerateFibonacci(n);
System.out.println("The sum of the even Fibonacci numbers is: "+result);
}
}
When n is small I get the right answer but for bigger values I get the wrong result. What’s the problem here?
intis limited to 32-bit accuracy,longto 64-bit.When you exceed the limit by adding numbers whose result is larger then the bit limit, they “roll over” and you lose the most significant bits from the result of the addition – essentially, they are “rounded” to 32/64 bits.
Here’s an example of rolling over:
Roughly speaking, each fibonnacci number is double the previous one, so roughly speaking you can only handle in the order of 64 iterations using a
longas the total.