+ 1

Why are there negative elements in array in this code?

public class Application { public static void main(String[] args) { long []a; a = new long[500]; a[0] = 1; a[1] = 2; int sum = 0; for (int i = 2; i < 500; ++i) { a[i] = a[i - 1] + a[i - 2]; //System.out.println(a[i]); if((a[i] == (a[i - 1] + a[i - 2])) && a[i] % 2 == 0) { System.out.println(a[i]); sum += a[i]; } } sum += 2; System.out.println("sum : " + sum); } }

2nd Aug 2017, 8:05 AM
Yusuf Saylam
Yusuf Saylam - avatar
6 Answers
+ 2
Here is how the code should look like using the BigInteger class. import java.math.BigInteger; public class Application { public static void main(String[] args) { BigInteger[] a = new BigInteger [500]; a[0] = new BigInteger("1") a[1] = new BigInteger("2") BigInteger sum = new BigInteger("0"); for (int i = 2; i < 500; ++i) { a[i] = a[i - 1].add(a[i - 2]); if (a[i].mod(a[1]).equals(new BigInteger("0"))) { System.out.println(a[i]); sum = sum.add(a[i]); } } sum = sum.add(a[1]); System.out.println("sum: " + sum); } }
2nd Aug 2017, 2:25 PM
Boris Batinkov
Boris Batinkov - avatar
+ 3
It is because the sum of arrays exceeded the limit of integer, which is 2147483647. For example, if you are trying to add 2147483647 (01111111111111111111111111111111(2)) and 1(00000000000000000000000000000001(2)), the result will be -2147483647(10000000000000000000000000000000(2)), which is negative.
2nd Aug 2017, 12:36 PM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 2
Use BigInteger. It is almost limitless type of integer.
2nd Aug 2017, 12:41 PM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 1
thank you i understand now but if i want to get the sum up to 4 million,what should i do?
2nd Aug 2017, 12:38 PM
Yusuf Saylam
Yusuf Saylam - avatar
+ 1
thank you very much boris!
2nd Aug 2017, 2:39 PM
Yusuf Saylam
Yusuf Saylam - avatar
0
https://code.sololearn.com/c6jhrBtgPJ7X/#java is there any mistake in this code?
2nd Aug 2017, 2:17 PM
Yusuf Saylam
Yusuf Saylam - avatar