forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheuler_totient_function.cpp
More file actions
49 lines (44 loc) · 871 Bytes
/
euler_totient_function.cpp
File metadata and controls
49 lines (44 loc) · 871 Bytes
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
/*Problem Statement:-
Given a number n, find the count of numbers from [1,n] that are
relatively prime to n i.e. gcd(n,x)=1
Solution:-
using euler totient function
*/
#include<iostream>
using namespace std;
int phi(int n) //less efficient but easy to understand
{
float result=n;
for(int f=2;f*f<=n;f++)
if(n%f==0)
{
while(n%f==0)
n/=f;
result*=(1.0-(1.0/(float)f));
}
if(n>1)
result*=(1.0-(1.0/(float)n));
return int(result);
}
int phi2(int n) //more efficient because of reduced number of multiplications
{
int result=n;
for(int f=2;f*f<=n;f++)
if(n%f==0)
{
while(n%f==0)
n/=f;
result-=result/f;
}
if(n>1)
result-=result/n;
return result;
}
int main()
{
cout<<"\nEnter a number : ";
int n;
cin>>n;
cout<<"\nCount of numbers from [1,n] that are relatively prime to n are : "<<phi2(n)<<endl;
return 0;
}