大数N阶乘算法
在做小数N阶乘时,使用递归算法,而当N数变大时,就不好算了因此谢了这个程序,来计算大数N阶乘,做了好长时间,希望对大家有所帮助。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "oj.h"
#define N 1000
/*
*将在数组中保存的字符串转成数字存到int数组中
*/
void getdigits1(int *a,char *s)
{
int i;
char digit;
int len = strlen(s);
//对数组初始化
for(i = 0; i < N; ++i)
*(a + i) = 0;
for(i = 0; i < len; ++i){
digit = *(s + i);
*(a + len - 1 - i) = digit - '0';//字符串s="12345",因此第一个字符应该存在int数组的最后一个位置
}
}
/*
*将数组a与数组b逐位相乘以后存入数组c
*/
void multiply2(int *a,int *b,int *c)
{
int i,j;
//数组初始化
for(i = 0; i < 2 * N; ++i)
*(c + i) = 0;
/*
*数组a中的每位逐位与数组b相乘,并把结果存入数组c
*比如,12345*12345,a中的5与12345逐位相乘
*对于数组c:*(c+i+j)在i=0,j=0,1,2,3,4时存的是5与各位相乘的结果
*而在i=1,j=0,1,2,3,4时不光会存4与各位相乘的结果,还会累加上上次相乘的结果.这一点是需要注意的!!!
*/
for(i = 0; i < N; ++i)
for(j = 0; j < N; ++j)
*(c + i + j) += *(a + i) * *(b + j);
/*
*这里是移位、进位
*/
for(i = 0; i < 2 * N - 1; ++i)
{
*(c + i + 1) += *(c + i)/10;//将十位上的数向前进位,并加上原来这个位上的数
*(c + i) = *(c + i)%10;//将剩余的数存原来的位置上
}
}
void CalcNN(int n, char *pOut)
{
int a[N],b[N],c[2*N];
char s1[N],s2[N];
int j = 2*N-1;
int i,k = 0,t = 0;
char chuan[100][100];
char temp[2];
char tempint[N];
if(n > 100 || n < 0)
return;
/******* 将n阶乘 需要乘的数全部变成字符串 *******/
for(k = 1; k <= n; k++)
{
itoa(k,chuan[k-1],10);
}
/****** 进行一步一步的相乘 不断递增 ******/
strcpy(s2,"1");
for(k = 0; k < n; k++)
{
strcpy(s1,chuan[k]);
getdigits1(a,s1);
getdigits1(b,s2);
multiply2(a,b,c);
while(c[j] == 0)
j--;
for(i = j;i >= 0; --i)
{
itoa(c[i],temp,10);
tempint[t] = temp[0] ;
t++;
}
tempint[t] = '\0';
strcpy(s2,tempint);
memset(tempint,0,N);
t = 0;
j = 2*N-1;
}
strcpy(pOut,s2);
// puts(pOut);
return;
}
主函数中需要分配大点内存给pOut,并且记得释放,n为阶乘数