I wrote this little program in java, and the value of f is always 0. I dont see the logical error.I did this exact same thing in python and it works flawlessly. I dont get what im missing.
public class factorial{
public static void main(String[] args){
int n = 1;
int f = 1;
while (true){
n ;
f = f * n;
System.out.println(f);
}
}
}
CodePudding user response:
In fact, you do not always get 0. Your output looks like this:
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
1932053504
1278945280
2004310016
2004189184
-288522240
-898433024
109641728
-2102132736
-1195114496
-522715136
862453760
-775946240
2076180480
-1853882368
1484783616
-1375731712
-1241513984
1409286144
738197504
-2147483648
-2147483648
0
0
0
0
...
This is problem with int overflow in infinite loop.
I don't familiar with Python, but if you want something int
without overflow, you can look at BigInteger
class in Java.