Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c - Why does N! stop overflowing the 32 bits output variable when N>=34?

Is there any limitation of variable overflow for big numbers? There is an exercise in a C book about factorials.

My code:

#include <stdio.h>

int main(void) {
    unsigned int n, fn, counter;
    //puts("enter nonnegative int");
    //scanf("%u", &n);
    n = 1;
    while (n != 34) {
        fn = n;
        counter = n - 1;
        while (counter > 0) {
            fn *= counter;
            counter--;
        }
        printf("%u
", fn);
        n++;
    }
}

The commented lines are for debugging.

This code prints the factorial of numbers from n(1) to 34 ('while(n!=34)'), but if you increase it to something like 36 it will just print 0 after first 34 outputs. I know most of the outputs are overflowed and am controlling these big numbers very poorly.

However, I would like to know what limits are causing these zeros to occur.

question from:https://stackoverflow.com/questions/65647449/why-does-n-stop-overflowing-the-32-bits-output-variable-when-n-34

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You complain that

N! stop overflowing the 32 bits output variable when N>=34

meaning that, after 34!, the result keeps remaining to 0.

Well, the answer is that it doesn't stop overflowing. What happens is that the value shown, that is the remainder of the division N! / 2^32 starting from N=34 becomes 0 and will never change.

In order to understand how it can happen, let's start with an example using a decimal number. We'll display the result of N! using a display with only two digits:

Factorial Actualresult Displayed result Notes
1! 1 01
2! 2 02
3! 6 06
4! 24 24
5! 120 20 Overflow!
6! 720 20 Overflow!
7! 5040 40 Overflow!
8! 40320 20 Overflow!
9! 362880 80 Overflow!
10! 3628800 00 Overflow and the shown value is 00!
11! 39916800 00 Overflow and the shown value is still 00!
12! 479001600 00 Overflow and the shown value is still 00!
.. .. 00 The shown value will be 00 forever

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...