#include <stdio.h>
int main(void) {
unsigned long long f;
int n;
printf("factorial:");
scanf("%d", &n);
printf("%d! = ",n);
f = n;
while (--n)
f*=n;
printf("%llu\n",f);
return 0;
}
I thought it would work endless loop in while-loop. However when I put negative number, it works. --> factorial : -1 -1! : 0 Why this thing happened? I wonder why zero was printed to the end. Pleaseeeeee help me.
CodePudding user response:
The while condition will execute till the condition is false. This means after the while loop !n
which in C is the same as n == 0
. If you subtract 1
from n = -1
sufficiently many times it will signed underflow and become positive and then eventually 0
. Hence it is not an infinite loop.
f
is unsigned and you multiply it by a negative number which then is interpreted as very large number. It turns out that with the input -1
at n == -67
f
becomes 0
due to unsigned overflow:
n f
-2 18446744073709551615
-3 2
-4 18446744073709551610
...
-65 9223372036854775808
-66 9223372036854775808
-67 0
...
2 0
1 0