+ 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); } }
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);
}
}
+ 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.
+ 2
Use BigInteger. It is almost limitless type of integer.
+ 1
thank you i understand now but if i want to get the sum up to 4 million,what should i do?
+ 1
thank you very much boris!
0
https://code.sololearn.com/c6jhrBtgPJ7X/#java
is there any mistake in this code?