How to compute the factorial of a number greater than 20 in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

/*
    A minimal big‑integer type using base‑10 digits.
    Digits are stored in reverse order (least significant first)
    to make multiplication straightforward.
*/
typedef struct {
    int *digits;        // dynamic array of digits
    size_t size;        // number of digits currently used
    size_t capacity;    // allocated capacity
} BigInt;

/*
    Initialize a BigInt with a small integer value.
*/
BigInt bigint_init(int value) {
    BigInt b;
    
    b.capacity = 32;                     // initial capacity
    b.size = 0;
    b.digits = malloc(b.capacity * sizeof(int));

    if (value == 0) {
        b.digits[b.size++] = 0;
    } else {
        while (value > 0) {
            b.digits[b.size++] = value % 10;
            value /= 10;
        }
    }
    
    return b;
}

/*
    Ensure the BigInt has enough capacity for new digits.
*/
void bigint_reserve(BigInt *b, size_t new_cap) {
    if (new_cap > b->capacity) {
        b->capacity = new_cap * 2;
        b->digits = realloc(b->digits, b->capacity * sizeof(int));
    }
}

/*
    Multiply BigInt by an integer n.
    Uses classic grade‑school multiplication.
*/
void bigint_multiply(BigInt *b, int n) {
    int carry = 0;

    for (size_t i = 0; i < b->size; ++i) {
        int product = b->digits[i] * n + carry;
        b->digits[i] = product % 10;
        carry = product / 10;
    }

    // Append remaining carry digits
    while (carry > 0) {
        bigint_reserve(b, b->size + 1);
        b->digits[b->size++] = carry % 10;
        carry /= 10;
    }
}

/*
    Convert BigInt to a printable string.
*/
char *bigint_to_string(const BigInt *b) {
    char *str = malloc(b->size + 1);
    
    for (size_t i = 0; i < b->size; ++i) {
        str[b->size - 1 - i] = '0' + b->digits[i];
    }
    str[b->size] = '\0';
    
    return str;
}

/*
    Compute factorial using BigInt.
*/
BigInt factorial_big(size_t n) {
    BigInt result = bigint_init(1);

    for (size_t i = 2; i <= n; ++i) {
        bigint_multiply(&result, (int)i);
    }

    return result;
}

/*
    Entry point: reads a number, computes factorial,
    and prints the result using big‑integer arithmetic.
*/
int main() {
    size_t n;

    printf("Enter a number greater than 20: ");
    scanf("%zu", &n);

    BigInt result = factorial_big(n);
    char *str = bigint_to_string(&result);

    printf("\nFactorial of %zu is:\n\n%s\n", n, str);

    free(result.digits);
    free(str);

    return 0;
}



/*
run:

Enter a number greater than 20: 25

Factorial of 25 is:

15511210043330985984000000

*/

 



answered Sep 11 by avibootz
...