1. 程式人生 > >[51nod1256]乘法逆元

[51nod1256]乘法逆元

esp cnblogs online log 註意 http code nco n!

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1256

解題關鍵:設$m \in {N_ + }$,則$a$在模$m$的意義下存在唯一的逆元,若$(a,m) \ne 1$,則$a$沒有模$m$的逆元;

法一:費馬小定理求解${a^{\phi (p)}} = 1\bmod p$

 1 #include<bits/stdc++.h>
 2 #define PI  acos(-1.0)
 3 using namespace std;
 4 typedef long long ll;
 5 ll mod_pow(ll x,ll n,ll p){
6 ll res=1; 7 while(n){ 8 if(n&1) res=res*x%p; 9 x=x*x%p; 10 n>>=1; 11 } 12 return res; 13 } 14 ll euler_phi(int n){ 15 int res=n; 16 for(int i=2;i*i<=n;i++){ 17 if(n%i==0){ 18 res=res/i*(i-1); 19 while
(n%i==0) n/=i; 20 } 21 } 22 if(n!=1) res=res/n*(n-1); 23 return res; 24 } 25 26 27 int main(){ 28 int a,b; 29 cin>>a>>b; 30 ll m=euler_phi(b)-1; 31 ll ans=mod_pow(a,m,b); 32 cout<<ans<<endl; 33 return 0; 34 }

法二:拓展歐幾裏得算法求解

註意x可能為負,但不會超過-b

 1 #include<bits/stdc++.h>
 2 #define PI  acos(-1.0)
 3 using namespace std;
 4 typedef long long ll;
 5 ll x,y;
 6 ll extgcd(ll a,ll b,ll &x,ll &y){
 7     ll d=a;
 8     if(b){
 9         d=extgcd(b,a%b,y,x);
10         y-=a/b*x;
11     }
12     else{
13         x=1,y=0;
14     }
15     return d;
16 }
17 int main(){
18     int a,b;
19     cin>>a>>b;
20     extgcd(a,b,x,y);
21     cout<<(x+b)%b<<endl;
22     return 0;
23 }

[51nod1256]乘法逆元