这次给大家带来一道水题,想到了方法还是很简单的
题目
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)!
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的取值范围在1 <=N <=1000000000000000000000000000000000000000000000,
我一开始的想法也是用大整数然后存储在数组中,但这种方法未免太复杂了吧。再看题目要求是输出n%2009的结果,那么很容易想到的是当n>=2009时输出的不就都是零了嘛,于是有以下代码一。
在代码一的基础上想到2009/7=287,于是缩小范围n>=287时输出的全为零,于是有以下代码二。
在代码二的基础上再次简化,在n>40时输出的全为零,于是有以下代码三。
代码一
#include<stdio.h>
int main(){
int result,n,i;
while(scanf("%d",&n)!=EOF){
result = 1;
if(n>=2009)
printf("0\n");
else{
for(i=2;i<=n;i++)
result = result*i%2009;
printf("%d\n",result);
}
}
return 0;
}
代码二
#include<stdio.h>
int main(){
int result,n,i;
while(scanf("%d",&n)!=EOF){
result = 1;
if(n>=287)
printf("0\n");
else{
for(i=2;i<=n;i++)
result = result*i%2009;
printf("%d\n",result);
}
}
return 0;
}
代码三
#include<stdio.h>
int main(){
int result,n,i;
while(scanf("%d",&n)!=EOF){
result = 1;
if(n>40)
printf("0\n");
else{
for(i=2;i<=n;i++)
result = result*i%2009;
printf("%d\n",result);
}
}
return 0;
}