Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

product of thirteen 9s are different in both approach in java [duplicate]

Tags:

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

like image 912
Prince Avatar asked Dec 09 '22 07:12

Prince


1 Answers

In your first attempt, you don't make sure the result is long. Therefore - it overflows as int.

product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
like image 173
Uri Agassi Avatar answered Dec 13 '22 22:12

Uri Agassi