public static Callable<String> getTask(final int i) {
return new Callable<String>() {
@Override
public String call() throws Exception {
BigInteger sum = BigInteger.ZERO;
for (int j = 1; j <= i; j++){
sum = sum.add(BigInteger.valueOf(j));
}
return sum.toString();
}
};
}
Andrei
Level 41
What are arbitrarily long numbers and why do they use BigInteger?
Resolved
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
18 May 2021, 14:09solution
BigInteger is a class that holds non-decimal numbers much larger than any primitive (byte, short, int, long) can hold. In this task, if you use a primitive and it ever goes over the max value of that primitive, the bytes flip and your results will be all messed up. Take, for example, this:
results:
2147483632 = 1111111111111111111111111110000
2147483637 = 1111111111111111111111111110101
2147483642 = 1111111111111111111111111111010
2147483647 = 1111111111111111111111111111111
-2147483644 = 10000000000000000000000000000100
-2147483639 = 10000000000000000000000000001001
-2147483634 = 10000000000000000000000000001110
-2147483629 = 10000000000000000000000000010011
-2147483624 = 10000000000000000000000000011000
-2147483619 = 10000000000000000000000000011101
At the fifth loop cycle adding 5 goes over the max value an integer can hold. At that point the bits flip (0's become 1's and 1's become 0's). the outputs here includes the binary representation of each number and you can see how this occurs on the 5th output.
With the BigInteger class, this won't occur. It has no max cap and can store numbers as large as you need, only restricted by the physical amount of memory the computer has.
+3
Andrei
19 May 2021, 06:09
Ah, I see. So 'arbitrarily long numbers' is just a huge number, it has nothing to do with actual long variable from Java. The phrasing is what was confusing me.
Now it makes sense why BigInteger is needed.
Thanks!
+1