Euler Phi's Function

Learn about the Euler Phi's function that can be used to solve many coding problems.

We'll cover the following

Introduction

Euler’s Phi function (also known as totient function, denoted by ϕ\phi) is a function on natural numbers that gives the count of positive integers co-prime with the corresponding natural number, i.e., the numbers whose GCD (Greatest Common Divisor) with N is 1. So we can say the following:

ϕ\phi(1) = 1 because gcd(1, 1) is 1.

ϕ\phi(2) = 1 because gcd(1, 2) is 1, but gcd(2, 2) is 2.

ϕ\phi(3) = 2 because gcd(1, 3) is 1 and gcd(2, 3) is 1.

ϕ\phi(4) = 2 because gcd(1, 4) is 1 and gcd(3, 4) is 1.

ϕ\phi(5) = 4 because gcd(1, 5) is 1, gcd(2, 5) is 1, gcd(3, 5) is 1 and gcd(4, 5) is 1.

ϕ\phi(6) = 2 because gcd(1, 6) is 1 and gcd(5, 6) is 1.

Solution

The value ϕ\phi(n) can be obtained by Euler’s formula. It basically says that the value of ϕ\phi(n) is equal to n multiplied by product of (1 – 1p\frac{1}{p}) for all prime factors p of n. For example, the value of ϕ\phi(6) = 6 * (1-12\frac{1}{2}) * (1 – 13\frac{1}{3}) = 2.

Now, let us look at the implementation of this function.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.