forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEuler Totient Function.cpp
60 lines (51 loc) · 949 Bytes
/
Euler Totient Function.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
/***********Method 1 - Using Prime Factorization**************/
/**********************O(sqrt(N))*****************************/
int etf(int n)
{
int res = n;
for(int i =2; i*i <=n ; i++)
{
if(n%i==0)
{
res /= i;
res *=(i-1);
while(n%i ==0)
n /=i;
}
}
if(n > 1)
{
res /= n;
res *= (n-1);
}
return res;
}
/******************Method 2 - Using Sieve*********************/
/**********************O(sqrt(N))*****************************/
int euler[1000001];
void etfsieve()
{
for(int i=1; i<1000001; i++)
euler[i] = i;
for(int i=2; i<1000001; i++)
{
if(euler[i] == i)
{
for(int j =i; j<1000001; j += i)
{
euler[j] /= i;
euler[j] *= (i-1);
}
}
}
}
int main()
{
etfsieve();
for(int i=1; i<501; i++)
cout<<etf(i)<<endl;
for(int i=1; i<501; i++)
cout<<i<<": "<<euler[i]<<endl;
}