forked from Raj04/Coding-Ninjas
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathEuler_pranshu.cpp
54 lines (42 loc) · 906 Bytes
/
Euler_pranshu.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
// C++ program to calculate Euler's
// Totient Function using Euler's
// product formula
#include <bits/stdc++.h>
using namespace std;
int phi(int n)
{
// Initialize result as n
float result = n;
// Consider all prime factors of n
// and for every prime factor p,
// multiply result with (1 - 1/p)
for(int p = 2; p * p <= n; ++p)
{
// Check if p is a prime factor.
if (n % p == 0)
{
// If yes, then update n and result
while (n % p == 0)
n /= p;
result *= (1.0 - (1.0 / (float)p));
}
}
// If n has a prime factor greater than sqrt(n)
// (There can be at-most one such prime factor)
if (n > 1)
result *= (1.0 - (1.0 / (float)n));
return (int)result;
}
// Driver code
int main()
{
int n;
for(n = 1; n <= 10; n++)
{
cout << "Phi" << "("
<< n << ")" << " = "
<< phi(n) <<endl;
}
return 0;
}
// This code is contributed by koulick_sadhu