#include <stdio.h>
int main()
{
int n; //階乘大小
printf("請輸入n的大小:");
scanf("%d",&n); //從鍵盤接收階乘大小
int a[200]; //確保保存最終運算結果的數組足夠大
int carry; //進位
int digit = 1; //位數
a[0] = 1; //將結果先初始化爲1
int temp; //階乘的任一元素與臨時結果的某位的乘積結果
for(int i = 2; i <= n; ++i) //開始階乘,階乘元素從2開始依次“登場”
{
//按最基本的乘法運算思想來考慮,將臨時結果的每位與階乘元素相乘
for(int j = 1, carry = 0; j <= digit; ++j)
{
temp = a[j-1] * i + carry; //相應階乘中的一項與當前所得臨時結果的某位相乘(加上進位)
a[j-1] = temp % 10; //更新臨時結果的位上信息
carry = temp / 10; //看是否有進位
}
while(carry) //如果有進位
{
a[++digit-1] = carry % 10; //新加一位,添加信息。位數增1
carry /= 10; //看還能不能進位
}
}
printf("結果是:/n%d ! = ",n); //顯示結果
for(int i = digit; i >=1; --i)
{
printf("%d",a[i-1]);
}
return 0;
}
m=n=count=0;
for(m=5;m<=500; m++)
{
n=m;
while(n%5==0)
{
n=n/5;
count++;
}
}
printf("%d/",count);
==================================================================================
在面試中,對於階乘方面有可能有兩個算法,一個是求大數階乘的問題,由於大數會超過整數的限值,所以需要使用數組的方法來實現:算法如下:
unsigned int result[10000];
#define N 100
int main(int arc, char** arg)
{
int i,j,k;
i=j=0;
k=1;
for(j=0; j<10000; j++)
{
result[j]=0;
}
result[0]=1;
for( i=1; i<=N; i++)
{
for( j=0; j<k; j++)
{
result[j]*=i;
}
for(j=0; j<k; j++)
{
if(result[j]/10000>=1)
{
result[j+1]+=result[j]/10000;
result[j]= result[j]%10000;
if(j==k-1)
k++;
}
}
}
printf("%d",result[k-1]);
for(j=k-2; j>=0; j--)
printf("%04d",result[j]);
getchar();
return 0;
}
m=n=count=0;
for(m=5;m<=500; m++)
{
n=m;
while(n%5==0)
{
n=n/5;
count++;
}
}
printf("%d/n",count);