GCC
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 3867 Accepted Submission(s): 1272
Problem Description
The GNU Compiler Collection (usually shortened to GCC) is a compiler system produced by the GNU Project supporting various programming languages. But it doesn’t contains the math operator “!”.
In mathematics the symbol represents the factorial operation. The expression n! means "the product of the integers from 1 to n". For example, 4! (read four factorial) is 4 × 3 × 2 × 1 = 24. (0! is defined as 1, which is a neutral element in multiplication, not multiplied by anything.)
We want you to help us with this formation: (0! + 1! + 2! + 3! + 4! + ... + n!)%m
In mathematics the symbol represents the factorial operation. The expression n! means "the product of the integers from 1 to n". For example, 4! (read four factorial) is 4 × 3 × 2 × 1 = 24. (0! is defined as 1, which is a neutral element in multiplication, not multiplied by anything.)
We want you to help us with this formation: (0! + 1! + 2! + 3! + 4! + ... + n!)%m
Input
The first line consists of an integer T, indicating the number of test cases.
Each test on a single consists of two integer n and m.
Each test on a single consists of two integer n and m.
Output
Output the answer of (0! + 1! + 2! + 3! + 4! + ... + n!)%m.
Constrains
0 < T <= 20
0 <= n < 10^100 (without leading zero)
0 < m < 1000000
Constrains
0 < T <= 20
0 <= n < 10^100 (without leading zero)
0 < m < 1000000
Sample Input
1 10 861017
Sample Output
593846
Source
昨天刚开始看到这道题,觉得是一道大数题,开始看到其他人也在做这道题,但是他们都超时了,所以我觉得应该就不是普通的大数题那么简单,后来整理了一下思路,发现了可以优化,如果n>=m的时候,后面的数对m取余得到的结果都是0,所以我们想到可以在这里进行优化,但是还是觉得要用大数题去做,我就套了一个大数阶乘的模板,输入了100000的测试数据进行测试,发现几秒钟都得不出结果,我们就觉得我们的思路有问题就放弃了没去做这道题了,后面看了一下别人的思路,发现我们的那种优化思想还是对的,只不过不要按照那种大数阶乘的思路去做,我们直接一边算阶乘一边进行取余,这样就不会超时了;还是题目做的太少了,很多知识都还不能灵活运用啊,这个题目应该还是可以解决的!
下面是代码:
#include <cstdio>
#include <cstring>
char s[120];
long long m,n,sum,ans;
int main()
{
int t,len;
scanf("%d",&t);
while(t--)
{
sum=ans=1;
scanf("%s%I64d",s,&m);
len=strlen(s);
/*if(m==1)//这里是考虑 n=0,m=1的那种情况,直接输出1,
{
printf("0\n");
continue;
}*/
if(len>7)
{
n=m-1; //当n>=m时,n!对m取余为0
}
else
{
n=0;
for(int i=0;i<len;i++)//把字符串转化为数字
n=n*10+s[i]-'0';
}
//求阶乘取余
for(int i=1;i<=n;i++)
{
sum=(sum*i)%m;//求阶乘取余
ans=(sum+ans)%m;//阶乘和取余
}
printf("%I64d\n",ans);//考虑到特殊情况,我们还可以直接再最后进行一次取余运算 ans%m;
}
}