输入N和P(P为质数),求N! Mod P = ? (Mod 就是求模 %)
例如:n = 10, P = 11,10! = 3628800
3628800 % 11 = 10
10 11
10
思路:(a+b)%m=(a%m+b%m)%m; a*b%m=a%m*b%m;
#include<cstdio>
#include<cstring>
using namespace std;
long long n,p,num;
int main()
{
while(scanf("%d %d",&n,&p)!=EOF)
{
long long num=1;
if(n==0)
printf("%lld\n",1);
else
{
for(int i=1;i<=n;i++)
num=num%p*i%p;
printf("%lld\n",num);
}
}
return 0;
}
另一种实现方法:
#include<cstdio>
long long n,p,ans=1;
int main(){
scanf("%I64d%I64d",&n,&p);
for(int i=1;i<=n;i++)
ans=ans*i%p;
printf("%I64d\n",ans);
return 0;
}