Search code examples
cfact

C / Find 190! (factorial) in c programming


I try to find 190! in C.

I define my variable to long double, but I see that it calculate (correctly) only to 172!:

After that, I got #INF00000...`

There is any way to do it?


Solution

  • It's really just a few lines of code to implement enough of a bigint implementation to compute factorials. Here's code that prints the first 200 factorials.

    #include <stdio.h>
    
    int mult(int n, size_t size, unsigned char *data) {
        int carry = 0;
        for (int i = 0; i < size; i++) {
            int result = data[i] * n + carry;
            data[i] = result % 100;
            carry = (result - data[i]) / 100;
        }
        return carry != 0;
    }
    
    void print(size_t size, unsigned char *data) {
        int first = 1;
        for (int i = 0; i < size; i++) {
            int d = data[size - i - 1];
            if (first && d == 0) continue;
            printf("%0*d", first && d < 10 ? 1 : 2, d);
            first = 0;
        }
    }
    
    int main(int argc, char*argv[]) {
        for (int fact = 1; fact <= 200; fact++) {
            unsigned char data[1000] = {1};
            for (int i = 1; i <= fact; i++) {
                if (mult(i, sizeof(data), data)) {
                    return 1;
                }
            }
            printf("%d! = ", fact);
            print(sizeof(data), data);
            printf("\n");
        }
        return 0;
    }