题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1008
基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题 收藏 关注
输入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^n%p = (((a*a%p)*a%p)*a%p)… 还需要注意的是范围问题,int 的最大值不超过 3*10^9。为了防止中间数据溢出,最好使用 long long 类型。下面是代码
#include <iostream>
using namespace std;
int main() {
long long n,p, res=1;
cin >> n >> p;
for(int i=1;i<=n;i++) {
res *= i;
res %= p;
}
cout << res << endl;
return 0;
}