1

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?

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
Mourad Kourie
  • 307
  • 1
  • 9

2 Answers2

6

The number you're calculating is quite big... too big for a Long. Since you're doing integer calculations, replace the long for a BigInteger. Since BigInteger is an object, you won't be able to use the + or % operators, and you'll need to use the method calls add() and mod().

Augusto
  • 28,839
  • 5
  • 58
  • 88
2

The maximum value a long can take is 9223372036854775807 (Long.MAX_VALUE). If the result of an addition exceeds that, it will overflow and return a negative value :

long x = 8838822096666553613L;
long y = 9212367363430683303L;
y = x + y;

will result in a y value of -395554613612314700. Therefore this comparison will fail :

if (x > y) {

and this is why you only see Y values getting printed

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82