输入N和P(P为质数),求N! Mod P = ? (Mod 就是求模 %)
例如:n = 10, P = 11,10! = 3628800
3628800 % 11 = 10
Input
两个数N,P,中间用空格隔开。(N < 10000, P < 10^9)
Output
输出N! mod P的结果。
Input示例
10 11
Output示例
10
注意一个数学公式
多项式展开:
(a*b)%p=(a%p*b)%p) = (a%p)*(b%p)%p;
刚开始我的错误代码是:
#include<iostream>
using namespace std;
int main()
{
long long n,p,i,x;
cin >> n >> p;
x = 1;
for(i = 1;i <= n;i++)
x = x * i;
x = x % p;
cout << x << endl;
return 0;
}
这样过不了第五个测试数据
89 263
217
因为这样写会超出longlong的范围,所以要边模边乘,利用数学公式
然后改为
#include<iostream>
using namespace std;
int main()
{
long long n,p,i,x = 1;
cin >> n >> p;
for(i = 1;i <= n;i++)
{
x *= i;
x %= p;
}
cout << x << endl;
return 0;
}
这样,就A了,主要是那个数学公式