N!Again
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4358 Accepted Submission(s): 2311
Problem Description
WhereIsHeroFrom: Zty, what are you doing ?
Zty: I want to calculate N!......
WhereIsHeroFrom: So easy! How big N is ?
Zty: 1 <=N <=1000000000000000000000000000000000000000000000…
WhereIsHeroFrom: Oh! You must be crazy! Are you Fa Shao?
Zty: No. I haven's finished my saying. I just said I want to calculate N! mod 2009
Hint : 0! = 1, N! = N*(N-1)!
Zty: I want to calculate N!......
WhereIsHeroFrom: So easy! How big N is ?
Zty: 1 <=N <=1000000000000000000000000000000000000000000000…
WhereIsHeroFrom: Oh! You must be crazy! Are you Fa Shao?
Zty: No. I haven's finished my saying. I just said I want to calculate N! mod 2009
Hint : 0! = 1, N! = N*(N-1)!
Input
Each line will contain one integer N(0 <= N<=10^9). Process to end of file.
Output
For each case, output N! mod 2009
Sample Input
4 5
Sample Output
24 120
题意:
求n的阶乘对2009取余的结果
分析:
根据同余定理(不知道?那就百度吧),只要对每个数取余并且依次取余,得到的结果不变,代码如下.....
#include<stdio.h>
int main()
{
int n,i,s;
while(~scanf("%d",&n))
{
s=1;
for(i=2;i<=n;++i)
{
s*=(i%2009);
s%=2009;
}
printf("%d\n",s);
}
return 0;
}
但是...这个代码是超时的........
再想,n的阶乘,当乘到n=2009时,不是已经满足n的阶乘对2009取余为0了吗?
所以大于2009的数只要乘到2009就可以了,大于等于2009的就是 0 ......
重新加了一条语句,过了....
#include<stdio.h>
int main()
{
int n,i,s;
while(~scanf("%d",&n))
{
s=1;
if(n>=2009)
{
printf("0\n");
continue;
}
for(i=2;i<=n;++i)
{
s*=(i%2009);
s%=2009;
}
printf("%d\n",s);
}
return 0;
}
让我们继续分析,2009不是一个质数,他可以分解为7*7*41,那么在乘阶乘的时候,乘到7,可以除去一个7,乘到14还可以消掉另一个7,乘到41还能消掉41,到这后面的就一定都是零了,别问为什么,这是分解质因数那种思想,不懂的要多百度哦~
这样下来就算是非常好的程序了...........
#include<stdio.h>
int main()
{
int n,i,s;
while(~scanf("%d",&n))
{
s=1;
if(n>=41)//取余后一定为零
{
printf("0\n");
continue;
}
for(i=2;i<=n;++i)//正常运算....
{
s*=(i%2009);
s%=2009;
}
printf("%d\n",s);
}
return 0;
}
/*
2016年2月2日19:33
*/
#include<stdio.h>
int main()
{
int n,x[50]={1};
for(int i=1;i<42;++i)
{
x[i]=(x[i-1]*i)%2009;
}
while(~scanf("%d",&n))
{
int ans=0;
if(n<41)
{
ans=x[n];
}
printf("%d\n",ans);
}
return 0;
}