简体   繁体   中英

How to handle large numbers?

I am trying to solve the following problem

you should calculate the difference between the square of the sum of the first n integers and the sum of the squares of the first n integer.

When I enter a large number (eg 4094574264) the answer is negative. Why? It should be a positive number.

Scanner scan = new Scanner(System.in);
long input = scan.nextLong();
long answer = (input * (input + 1) / 2)*(input * (input + 1) / 2) - (input * (input + 1)) * ((input * 2) + 1) / 6;
System.out.println(answer);

The problem is in this line

(input * (input + 1) / 2)*(input * (input + 1) / 2) - (input * (input + 1)) * ((input * 2) + 1) / 6

4094574264 is a 33-bit signed number, therefore input * (input + 1) will need 66 bits to store, which overflows 64-bit long . That's not counting the series of multiplications later, resulting in a result much larger than 64 bits.

If you want to do such high precision arithmetic, use BigInteger instead

You, my friend, are experiencing overflow . This is when there aren't enough bits to describe the number that you want to explain, so you end up going around in a big loop (hence the negative numbers).

The solution, if you wish to use incredibly large numbers, is to use the BigInteger and BigDecimal class. These are designed to create arbitrary precision numbers.

Low-level answer:

The answer is negative because you're experiencing overflow. The JVM can only represent numbers up to a certain value (the maximum for that type.) If you perform any operation which increases a value beyond the maximum, it "flows over" the machine's representation capabilities and changes the number completely; in your case, to a negative value. The opposite applies to negatives: if I decrease a negative value below the minimum, it will "flow under" and I will get an answer that is a very large positive. Use BigInteger ( https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html ) for "large math."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM