Summary of the question-the Queen Mother and the Queen Mother are embarrassed to be a Chashan Niu again
Original title link
The Queen Mother and the Queen Mother are bothered by her screams again
topic
Problem analysis:
This question is to find the value of the third factorial modulus of a positive integer, which involves the problem of data overflow
Question ideas:
-
If you use a violent method to solve this problem, that is, first find the value of the third factorial and then take the modulus, the data will definitely overflow.
-
According to the title, we can see that the maximum value of m is 1e9, and we can know from experience that the third factorial of 4 must be much greater than 1e9, that is to say, when n>=4, (n!!!)%m must be Equal to 0 (because n!!! is much larger than m); when n=3, find 3!!! and then take the modulus of m; when 0<=n<=2, n!!!= n, this (n!!!)%m=n%m, this way can be solved
Code
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,m,i;
cin>>t;
while(t--)
{
cin>>n>>m;
if(n<=2)
{
cout<<n%m<<endl;
}
else if(n>=4)
{
cout<<"0"<<endl;
}
else
{
long long sum=1;
for(i=1;i<=720;i++)
{
sum*=i;
sum%=m;
}
cout<<sum<<endl;
}
}
return 0;
}
Gain from doing the problem
-
Pay attention to the scope of the given data when doing the questions. Some seemingly complex problems may be solved because the data scope is relatively small, and some clever solutions can be thought of, so as to achieve the effect of getting twice the result with half the effort.
-
Memorizing some common integer factorial values, there may be some unexpected benefits when doing the problem
My blog will be synced to Tencent Cloud + community soon, and everyone is invited to join: https://cloud.tencent.com/developer/support-plan?invite_code=1459rh1icdi42