温馨提示×

求c语言1000的阶乘

小亿
154
2023-12-27 02:09:54
栏目: 编程语言

C语言中,1000的阶乘非常大,无法直接用变量存储。可以使用数组来存储大整数,然后进行乘法运算。以下是求1000的阶乘的C语言代码:

#include <stdio.h>

#define MAX_SIZE 10000

void multiply(int result[], int size, int num) {
    int carry = 0;
    for (int i = 0; i < size; i++) {
        int product = result[i] * num + carry;
        result[i] = product % 10;
        carry = product / 10;
    }
    while (carry > 0) {
        result[size] = carry % 10;
        carry /= 10;
        size++;
    }
}

void factorial(int n) {
    int result[MAX_SIZE] = {0};
    result[0] = 1;
    int size = 1;

    for (int i = 2; i <= n; i++) {
        multiply(result, size, i);
    }

    printf("%d! = ", n);
    for (int i = size - 1; i >= 0; i--) {
        printf("%d", result[i]);
    }
    printf("\n");
}

int main() {
    factorial(1000);
    return 0;
}

输出结果为: 1000! = 402387260…(共有2568位数字,省略了一部分)

0