N!Again
2014-8-5 21:11
(同余定理加上特殊情况)
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
分析,因为这个题的特殊性在于阶乘,所以只要在某个阶乘下能出现2009及其倍数,就可以满足
2009=7*7*41=41*49;
只用判断到41既可,因为41的阶乘下有7和14,是2009的2倍,完全可以实现。 41以内的就要用到同余定理了
代码如下:
#include<stdio.h>
__int64 mod(int n)
{
__int64 sum=1;
while(n>=1)
{
sum*=n;
sum%=2009;
n--;
}
return sum;
}
int main()
{
__int64 n;
while(~scanf("%I64d",&n))
{
if(n>=41) printf("0\n");
else printf("%d\n",mod(n)%2009);
}
return 0;
}