51nod 1008 N的阶乘 mod P

时间:2017-08-05 18:30:52   收藏:0   阅读:383
输入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

如果用普通的方法就会wa,如下所示
 1 #include <iostream>
 2 #include <stdio.h>
 3 using namespace std;
 4 int fac(int m){
 5     if(m==1) return 1;
 6     return m*fac(m-1);
 7 }
 8 int main(){
 9     long long n,p,t;
10     scanf("%I64d%I64d",&n,&p);
11     t=fac(n);
12     cout<<t%p<<endl;
13     return 0;
14 }
 
 
注意longlong Int 的使用以及边乘边求余(int的最大值不超过3*10^9)
  (a×b) mod c=(a mod c * b mod c) mod c
  a^n%p=(((a*a%p)*a%p)*a%p)  网上看到的不太懂

 

 1 #include <iostream>
 2 using namespace std;
 3 int main(){
 4     long long n,p,res=1;
 5     cin>>n>>p;
 6     for(int i=1;i<=n;i++){
 7         res*=i;
 8         res%=p;
 9     }
10     cout<<res<<endl;
11     return 0;
12 }

 

 

原文:http://www.cnblogs.com/z-712/p/7290799.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!