The product of thirteen nines differs in both approaches in java

public class Main {

    public static void main(String[] args) {

        long product = 1L;
        product = (9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
        System.out.println(product);
        product = 9L;
        for (int i = 0; i != 12; i++) {
            product *= 9;
        }
        System.out.println(product);

    }
}

Output: -754810903
       2541865828329 // this one is correct.

+4
source share
2 answers

In the first attempt, you are not convinced that the result long. Therefore - it overflows like int.

product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
+7
source

This is due to the fact that the data type is intinsufficient to accept all this value.

Convert it to long.

product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);

Or at least drop it first. But make sure you get the data type value long. Otherwise, it will not work, and you will never get such a result. What did you want:)

+7
source

Source: https://habr.com/ru/post/1541935/


All Articles