1. 程式人生 > >歐拉函數(模板,相關問題持續更新中)

歐拉函數(模板,相關問題持續更新中)

sin 一個 技術分享 bsp 根據 stream 歐拉函數 正整數 static

歐拉函數是一個很有用的東東。可以被擴展用來解決許多與素數相關的問題,逆元問題,歐拉函數降冪等!

概念:歐拉函數是小於或等於n的正整數中與n互質的數的數目(特別地φ(1)=1),若n為質數可直接根據性質得出技術分享圖片,否則的話要求解。

求解模板:

 1 int Euler(int n)
 2 {
 3     if(n==1) return 1;
 4     int ans=n;
 5     
 6     for(int i=2;i*i<=n;++i)
 7     {
 8         if(n%i==0)
 9         {
10             while(n%i==0) n/=i;
11 ans=ans/i*(i-1); 12 } 13 } 14 if(n!=1) ans=ans/n*(n-1); 15 16 return ans; 17 }

歐拉函數求逆元:51nod1256

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 using namespace std;
 5 typedef long long ll;
 6 int mod;
 7  
 8 int Qpow(llo a,llo b)
9 { 10 int r=1; 11 while(b) 12 { 13 if(b&1)r=r*a%mod; 14 a=a*a%mod; 15 b>>=1; 16 } 17 18 return r; 19 } 20 21 int Euler(int n) 22 { 23 if(n==1) return 1; 24 int ans=n; 25 26 for(int i=2;i*i<=n;++i) 27 { 28 if(n%i==0
) 29 { 30 while(n%i==0) n/=i; 31 ans=ans/i*(i-1); 32 } 33 } 34 if(n!=1) ans=ans/n*(n-1); 35 36 return ans; 37 } 38 39 int main() 40 { 41 int a,b; 42 cin>>a>>b; 43 mod=b; 44 45 //llo ans=Qpow(a,mod-2);// mod質數 46 int ans=Qpow(a,Euler(mod)-1); 47 cout<<ans<<endl; 48 49 return 0; 50 }

完。

歐拉函數(模板,相關問題持續更新中)