歐拉函數


洛谷P2158

歐拉函數

在數論,對正整數n,歐拉函數是小於或等於n的正整數中與n互質的數的數目(因此φ(1)=1)。此函數以其首名研究者歐拉命名(Euler's totient function),它又稱為Euler's totient function、φ函數、歐拉商數等。 例如φ(8)=4,因為1,3,5,7均和8互質。 從歐拉函數引伸出來在環論方面的事實和拉格朗日定理構成了歐拉定理的證明。

簡單來說歐拉函數就是求從1到n-1中有多少個數與n互質。

歐拉函數的模板

 1 int a[maxn];
 2 void euler()
 3 {
 4     for(int i=1;i<=maxn;i++)
 5         a[i]=i;
 6         a[1]=0;
 7         for(int i=1;i<=maxn;i++)
 8         {
 9             if(a[i]==i)
10             {
11              for(int j=i;j<=maxn;j+=i)
12              a[j]=a[j]/i*(i-1);    
13             }
14         }
15 }

應用

洛谷這道題,簡單來說就是給一個N*N的矩陣,由左下角這個點可以和其他的點連多少條線,其中任意兩條線不能交叉。我們很容易可以想到用斜率來處理,因為只要兩條線的斜率不同他們就不會交叉,我們可以以左下角為原點建立坐標系,橫縱坐標都為0到N-1,那么我們可以很容易得出如果一個點的坐標互質,那么它就滿足題意,例如在4*4的矩陣中滿足題意的有(1,0)(0,1)(1,1)(2,1)(1,2)(3,1)(1,3)(3,2)(2,3),並且因為對稱關系,橫縱坐標軸以及對稱軸上的3個點我們做特殊處理,那么我們可以看到所有滿足題意的點的橫縱坐標都是互質的,那么我們只要根據對稱 ,統計這樣的數有多少個就可以了

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <algorithm>
 5 #include <queue>
 6 #include <stack>
 7 #include <stdio.h>
 8 #include <cmath>
 9 #include <string.h>
10 
11 using namespace std;
12 #define ll long long
13 #define maxn 40005
14 static const int WHITE=0;
15 static const int GRAY=1;
16 static const int BLACK=2;
17 static const int INF=(1<<20);
18 int a[maxn];
19 void euler()
20 {
21     for(int i=1;i<=maxn;i++)
22         a[i]=i;
23         a[1]=0;
24         for(int i=1;i<=maxn;i++)
25         {
26             if(a[i]==i)
27             {
28              for(int j=i;j<=maxn;j+=i)
29              a[j]=a[j]/i*(i-1);    
30             }
31         }
32 }
33 int main()
34 {
35   freopen("C:\\Users\\16599\\Desktop\\in.txt","r",stdin);
36   int N,ans=0;
37   cin>>N;
38   euler();
39   for(int i=1;i<=N-1;i++)
40   {
41     ans+=a[i]*2;
42   }
43   if(N==1)
44   cout<<"0"<<endl;
45   else
46   cout<<ans+3<<endl;
47   return 0;
48 }

 


免責聲明!

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



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