I am trying to calculate the sum of the first, even four million Fibonacci-numbers. However, after a while, only the Y-values are being printed out as the values get larger, even though I'm using the identifier long.
These are the start values:
long amount = 4000000;
long x = 1;
long y = 2;
long sum = 2;
Here is a for-loop that sums up and prints out the numbers as the program runs.
for (int i = 0; i < amount - 1; i++) {
if (x > y) {
y = x + y;
if (y % 2 == 0) {
sum += y;
}
System.out.println("X: " + x);
} else {
x = x + y;
if (x % 2 == 0) {
sum += x;
}
System.out.println("Y: " + y);
}
}
System.out.println("Summa: " + sum);
First Fibonacci numbers output correctly:
Y: 2
X: 3
Y: 5
X: 8
Y: 13
X: 21
Y: 34
X: 55
Y: 89
X: 144
Y: 233
X: 377
Output after a while:
X: 8838822096666553613
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Y: 9212367363430683303
Why is only Y
getting calculated after a while? Is my code wrong?