歐拉函數


一:歐拉函數

歐拉函數定義:

φ(x)=x(1-1/p(1))(1-1/p(2))(1-1/p(3))(1-1/p(4))…..(1-1/p(n)) 其中p(1),p(2)…p(n)為x

的所有質因數;x是正整數; φ(1)=1(唯一和1互質的數,且小於等於1)。注意:每種質因數只有一個。

 

 

歐拉函數性質:

(1)   p^k型歐拉函數:

若N是質數p(即N=p), φ(n)= φ(p)=p-p^(k-1)=p-1。

若N是質數p的k次冪(即N=p^k),φ(n)=p^k-p^(k-1)=(p-1)p^(k-1)。

(2)mn型歐拉函數

設n為正整數,以φ(n)表示不超過n且與n互素的正整數的個數,稱為n的歐拉函數值。若m,n互質,φ(mn)=(m-1)(n-1)=φ(m)φ(n)。

(3)特殊性質:

若n為奇數時,φ(2n)=φ(n)。

對於任何兩個互質 的正整數a,n(n>2)有:a^φ(n)=1 mod n (恆等於)此公式即 歐拉定理

當n=p 且 a與素數p互質(即:gcd(a,p)=1)則上式有: a^(p-1)=1 mod n (恆等於)此公式即 費馬小定理

 

歐拉函數模板O( n*sqrt(ai) ):

 

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n;
 4 
 5 int oula(int x)
 6 {
 7     int res=x;
 8     for(int i=2;i<=x/i;i++)
 9     {
10         if(x%i==0)
11         {
12             res=res/i*(i-1);
13             while(x%i==0)x/=i;
14         }
15     }
16     if(x>1)res=res/x*(x-1);
17     return res;
18 }
19 
20 int main()
21 {
22     scanf("%d",&n);
23     for(int i=1;i<=n;i++)
24     {
25         int a;
26         scanf("%d",&a);
27         printf("%d\n",oula(a));
28     }
29 
30     return 0;
31 }

 

篩法求歐拉函數模板

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int N=1e6+100;
 5 int n,primes[N],cnt,phi[N];  //phi存儲每個數的歐拉函數
 6 bool st[N];
 7 
 8 void get_eulers(int n)
 9 {
10     phi[1]=1;
11     for(int i=2;i<=n;i++)
12     {
13         if(!st[i])
14         {
15             primes[cnt++]=i;
16             phi[i]=i-1;
17         }
18         for(int j=0;primes[j]<=n/i;j++)
19         {
20             st[primes[j]*i]=1;
21             if(i%primes[j]==0)
22             {
23                 phi[primes[j]*i]=phi[i]*primes[j];
24                 break;
25             }
26             phi[primes[j]*i]=phi[i]*(primes[j]-1);
27         }
28     }
29 }
30 
31 int main()
32 {
33     scanf("%d",&n);
34     get_eulers(n);
35     
36     ll res=0;
37     for(int i=1;i<=n;i++)res+=phi[i];
38     printf("%lld\n",res);
39     
40     return 0;
41 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM