您的位置:首页 > 其它

大数的阶乘

2015-11-01 19:45 369 查看
#include<stdio.h>
#include<string.h>
/* 一个数组元素表示4 个十进制位,即数组是万进制的*/
#define BIGINT_RADIX 10000
#define RADIX_LEN 4
/* 10000! 有35660 位*/
#define MAX_LEN (35660/RADIX_LEN+1) /* 整数的最大位数*/
int x[MAX_LEN + 1];
/**
* @brief 打印大整数.
* @param[in] x 大整数,用数组表示,低位在低地址
* @param[in] n 数组x 的长度
* @return 无
*/
void bigint_print(const int x[], const int n) {
int i;
int start_output = 0; /* 用于跳过前导0 */
for (i = n - 1; i >= 0; --i) {
if (start_output) { /* 如果多余的0 已经都跳过,则输出*/
printf("%04d", x[i]);
} else if (x[i] > 0) {
printf("%d", x[i]);
start_output = 1; /* 碰到第一个非0 的值,就说明多余的0 已经都跳过*/
}
}
if(!start_output) printf("0"); /* 当x 全为0 时*/
}
/**
* @brief 大整数乘法, x = x*y.
* @param[inout] x x
* @param[in] y y
* @return 无
*/
void bigint_mul(int x[], const int y) {
int i;
int c = 0; /* 保存进位*/
for (i = 0; i < MAX_LEN; i++) { /* 用y,去乘以x 的各位*/
const int tmp = x[i] * y + c;
x[i] = tmp % BIGINT_RADIX;
c = tmp / BIGINT_RADIX;
}
}
/**
* @brief 计算n 的阶乘
* @param[in] n
* @param[out] x 存放结果
* @return 无
*/
void bigint_factorial(int n, int x[]) {
int i;
memset(x, 0, sizeof(int) * (MAX_LEN + 1));
x[0] = 1;
for (i = 2; i <= n; i++) {
bigint_mul(x, i);
}
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {//计算10000以内数字的阶乘
bigint_factorial(n, x);
bigint_print(x, MAX_LEN + 1);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: