Euler's Totient Function - GeeksforGeeks

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Tutorials Student Jobs Courses Sign In

Related Articles Save for later

Euler’s Totient Function


Difficulty Level : Medium ● Last Updated : 08 Nov, 2020

Euler ’s Totient function Φ (n) for an input n is the count of numbers


in {1, 2, 3, …, n} that are relatively prime to n, i.e., the numbers

whose GCD (Greatest Common Divisor) with n is 1.

Examples :

Φ(1) = 1
gcd(1, 1) is 1

Φ(2) = 1
gcd(1, 2) is 1, but gcd(2, 2) is 2.


Φ(3) = 2
gcd(1, 3) is 1 and gcd(2, 3) is 1

Φ(4) = 2
gcd(1, 4) is 1 and gcd(3, 4) is 1

Φ(5) = 4
WHAT’S NEW
gcd(1, 5) is 1, gcd(2, 5) is 1,
gcd(3, 5) is 1 and gcd(4, 5) is 1
Data Structures and
Φ(6) = 2 Algorithms – Self Paced
gcd(1, 6) is 1 and gcd(5, 6) is 1, Course
View Details

Recommended: Please solve it on “PR ACTICE” first, before

moving on to the solution.


Ad-Free Experience –
GeeksforGeeks Premium
How to compute Φ(n) for an input nΦ
View Details
A simple solution is to iterate through all numbers from 1 to n-1

and count numbers with gcd with n as 1. Below is the

implementation of the simple method to compute Euler ’s Totient

function for an input integer n. 

C++ C Java P ython3 C# PHP

 // A simple C++ program to calculate


// Euler's Totient Function
 #include <iostream>
using namespace std;

// Function to return gcd of a and b
 int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}

// A simple method to evaluate Euler Totient Function


int phi(unsigned int n)
{
unsigned int result = 1;
for (int i = 2; i < n; i++)
if (gcd(i, n) == 1)
result++;
return result;
}

// Driver program to test above function


int main()
{
MOST POPULAR IN
int n; MATHEMATICAL
for (n = 1; n <= 10; n++)
cout << "phi("<<n<<") = " << phi(n) << endl;
return 0; Program for Decimal to Binary
}
Conversion
// This code is contributed by SHUBHAMSINGH10
Merge two sorted arrays

Prime Numbers
Output : 

Program for Binary To Decimal


phi(1) = 1
Conversion
phi(2) = 1
How to swap two numbers without using
phi(3) = 2
phi(4) = 2
a temporary variable?
phi(5) = 4
phi(6) = 2
phi(7) = 6
phi(8) = 4
phi(9) = 6
phi(10) = 4

The above code calls gcd function O(n) times. The time complexit y

of the gcd function is O(h) where “h” is the number of digit s in a

smaller number of given two numbers. Therefore, an upper bound

on the time complexit y of the above solution is O(nLogn) [How Φ


there can be at most Log10n digit s in all numbers from 1 to n]

Below is a Better Solution. The idea is based on Euler ’s product

formula which states that the value of totient functions is below the

product overall prime factors p of n. 

MORE RELATED ARTICLES IN


MATHEMATICAL
Operators in C / C++

Find minimum number of coins that


make a given value

The formula basically says that the value of Φ(n) is equal to n Write a program to reverse digits of a
multiplied by product of (1 – 1/p) for all prime factors p of n. For
number
example value of Φ(6) = 6 * (1-1/2) * (1 – 1/3) = 2.
Program for factorial of a number
We can find all prime factors using the idea used in this post. 

Modulo Operator (%) in C/C++ with


1) Initialize : result = n Examples
2) Run a loop from 'p' = 2 to sqrt(n), do following for
a) If p divides n, then
Set: result = result * (1.0 - (1.0 / (float
Divide all occurrences of p in n.
3) Return result

Below is the implementation of Euler ’s product formula.  

C++ C Java P ython3 C# PHP

 // 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

Output : 

phi(1) = 1
phi(2) = 1
phi(3) = 2
phi(4) = 2
phi(5) = 4
phi(6) = 2
phi(7) = 6
phi(8) = 4
phi(9) = 6
phi(10) = 4

We can avoid floating-point calculations in the above method. The

idea is to count all prime factors and their multiples and subtract

this count from n to get the totient function value (Prime factors

and multiples of prime factors won’t have gcd as 1) 

1) Initialize result as n
2) Consider every number 'p' (where 'p' varies from 2 t
If p divides n, then do following
a) Subtract all multiples of p from 1 to n [all mult
will have gcd more than 1 (at least p) with n]
b) Update n by repeatedly dividing it by p.
3) If the reduced n is more than 1, then remove all mult
of n from result.

Below is the implementation of the above algorithm. 

C++ C Java P ython3 C# PHP

 // C++ program to calculate Euler's


// Totient Function
 #include <bits/stdc++.h>
using namespace std;
 int phi(int n)
 {
// Initialize result as n
int result = n;

// Consider all prime factors of n


// and subtract their multiples
// from result
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 -= result / p;
}
}

// If n has a prime factor greater than sqrt(n)


// (There can be at-most one such prime factor)
if (n > 1)
result -= result / n;

return 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

Output :  

phi(1) = 1
phi(2) = 1
phi(3) = 2
phi(4) = 2
phi(5) = 4
phi(6) = 2
phi(7) = 6
phi(8) = 4
phi(9) = 6
phi(10) = 4

Let us take an example to understand the above algorithm. 

n = 10.
Initialize: result = 10

2 is a prime factor, so n = n/i = 5, result = 5


3 is not a prime factor.

The for loop stops after 3 as 4*4 is not less than or e


to 10.

After for loop, result = 5, n = 5


Since n > 1, result = result - result/n = 4

Some Interesting Proper ties of Euler ’s Totient Func tion 

1) For a prime number p, Φ(p) is p-1. For example Φ(5) is 4, Φ(7)


is 6 and Φ(13) is 12. This is obvious, gcd of all numbers from 1 to p-
1 will be 1 because p is a prime.

2) For two numbers a and b, if gcd(a, b) is 1, then Φ(ab) = Φ(a) *


Φ(b). For example Φ(5) is 4 and Φ(6) is 2, so Φ(30) must be 8 as 5
and 6 are relatively prime. 

3) For any two prime numbers p and q, Φ(pq) = (p-1)*(q-1). This


proper t y is used in RS A algorithm. 

4) If p is a prime number, then Φ(p k


) = p
k
– p
k-1
. This can be proved

using Euler ’s product formula.

5) Sum of values of totient functions of all divisors of n is equal to

n. 

For example, n = 6, the divisors of n are 1, 2, 3 and 6. According to

Gauss, sum of Φ(1) + Φ(2) + Φ(3) + Φ(6) should be 6. We can


verif y the same by putting values, we get (1 + 1 + 2 + 2) = 6.

6) The most famous and impor tant feature is expressed in Euler ’s

theorem : 

The theorem states that if n and a are coprime


(or relatively prime) positive integers, then

aΦ(n) Φ 1 (mod n)

The RS A cr yptosystem is based on this theorem:

In the par ticular case when m is prime say p, Euler ’s theorem turns

into the so-called Fermat ’s little theorem : 

ap-1 Φ 1 (mod p)

7) Number of generators of a finite cyclic group under modulo n

addition is Φ(n).
Related Ar ticle : 

Euler ’s Totient function for all numbers smaller than or equal to n 

Optimized Euler Totient Function for Multiple Evaluations

References : 

http://e-maxx.ru/algo/euler_function

http://en.wikipedia.org/wiki/Euler%27s_totient_function

This ar ticle is contributed by Ankur. Please write comment s if you

find anything incorrect, or you want to share more information

about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the

impor tant DS A concept s with the DS A Self Paced Course at a

student-friendly price and become industr y ready.

 Like 0

 Previous Next 
Euler's Totient function Write an iterative
for all numbers smaller O(Log y) function for
than or equal to n pow(x, y)

RECOMMENDED ARTICLES Page : 1 2 3

Optimized Euler Count integers in a


01 Totient Function for 05 range which are
Multiple Evaluations divisible by their
26, Jun 17 euler totient value
13, Mar 19

Probability of Euler's
02
Totient Function in a
range [L, R] to be Count of elements
06
divisible by M having Euler's Totient
31, Jul 20 value one less than
itself
Check if Euler Totient 03, Jul 20

03 Function is same for


a given number and
twice of that number Perfect totient
10, Sep 20
07 number
26, Jun 20

Euler's Totient
04
function for all
numbers smaller Highly Totient
08
than or equal to n Number
14, Nov 15 30, Jul 19

Ar ticle Contributed By :

GeeksforGeeks

Vote for di culty

Current di culty : Medium

Easy Normal Medium Hard Expert

Improved By : nitin mittal, Sam007, jit_t, Smitha Dinesh Semwal,


Mithun Kumar, SHUBHAMSINGH10,
lalitvavdara2016, koulick_sadhu
Article Tags : euler-totient , GCD-LCM , Modular Arithmetic ,
number-theory , Numbers , Prime Number , sieve ,
Mathematical
Practice Tags : number-theory, Mathematical, Prime Number,
Numbers, sieve, Modular Arithmetic

Improve Article Report Issue

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

Company Learn Practice Contribute


About Us Algorithms Courses Write an Article
5th Floor, A-118,
Sector-136, Noida, Uttar Pradesh - 201305 Careers Data Structures Company-wise Write Interview Experience
feedback@geeksforgeeks.org Privacy Policy Languages Topic-wise Internships
Contact Us CS Subjects How to begin? Videos
Copyright Policy Video Tutorials

@geeksforgeeks , Some rights reserved

You might also like