In java int
is 4 bytes long which has range of -2,147,483,648 to 2,147,483, 647. So in your case int
sum
is overflowing. Because when n = 50 febonacci series gives result as 12586269025. Which is beyond the limit of int
.
So you should rather use a long
to hold the sum
. Which is 8 bytes with limit of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Even you need to use long array, because you are performing operations after assigning values to array elements. So updated code should be:
long sum = 0;
final long a[] = new long[50];
a[0] = 1L;
a[1] = 2L;
final int n = 50;
for (int i = 2; i < n; i++) {
a[i] = a[i - 1] + a[i - 2];
if (a[i] < n && i % 2 == 0) {
sum = sum + a[i];
}
}
System.out.println(sum);
Note (as suggested by Mihir): long
is also having limitations, so till n = 92, it will work fine. If you can have n > 92 you need to use BigInteger
. Which is also having further limits. So consider these limitations in your code.
BigInteger must support values in the range -2Integer.MAX_VALUE
(exclusive) to +2Integer.MAX_VALUE (exclusive) and may support values
outside of that range.
Implementation note: BigInteger constructors and operations throw
ArithmeticException when the result is out of the supported range of
-2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive).