GCC
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 4266 Accepted Submission(s): 1401
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
这道题首先要想到。6%2是不是余0.(2*x)%2是不是0.所以这里,我们可以知道,n! % m在n大于等于m的时候,肯定就和n没有关系了。答案就是0.吧多余的部分去掉之后直接算就好了。还有一点要注意的是ANS最后需要加上1,应为还有0!,但是加上一之后还需要%m。自己仔细想想是不是这样子吧。
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int main()
{
long long T;
cin >> T;
while(T--)
{
long long m;
string s;
cin >> s >> m;
long long w;
long long cnt = 0;
long long g = 1;
long long ans = 0;
if(s.length()>8)
w = m;
else
{
for(int i=0;i<s.length();i++)
cnt = cnt*10+(s[i]-'0');
w = min(m,cnt);
}
for(int i=1;i<=w;i++)
{
g = (g%m)*(i%m)%m;
ans = (ans+g)%m;
}
cout<<(ans+1)%m<<endl;
}
return 0;
}