VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-elements-having-eulers-totient-value-one-less-than-itself/

⇱ Count of elements having Euler's Totient value one less than itself - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of elements having Euler's Totient value one less than itself

Last Updated : 15 Jul, 2025

Given an array arr[] of N integers, and a range L to R, the task is to find the total number of elements in the array from index L to R that satisfies the following condition:


 

where F(x) is Euler's Totient Function.


 


Examples:

Input: arr[] = {2, 4, 5, 8}, L = 1, R = 3 
Output:
Explanation: 
Here in the given range, F(2) = 1 and (2 - 1) = 1. Similarly, F(5) = 4 and (5 - 1) = 4. 
So the total count of indices which satisfy the condition is 2. 
Input: arr[] = {9, 3, 4, 6, 8}, L = 3, R = 5 
Output:
Explanation : 
In the given range there is no element that satisfies the given condition. 
So the total count is 0.


Naive Approach: The naive approach to solve this problem is to iterate over all the elements of the array and check if the Euler's Totient value of the current element is one less than itself. If yes then increment the count.
Time Complexity: O(N * sqrt(N)) 
Auxiliary Space: O(1)
Efficient Approach:

Euler’s Totient function F(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 Greatest Common Divisor with n is 1.

  1. If we observe, we can notice that the above given condition is only satisfied by the Prime numbers.
  2. So, all we need to do is to compute the total numbers of prime numbers in the given range.
  3. We will use Sieve of Eratosthenes to compute prime numbers efficiently.
  4. Also, we will pre-compute the numbers of primes numbers in a count array.


Below is the implementation of the above approach.


Output: 
2

Time Complexity: O(N * log(logN)) 
Auxiliary Space: O(N)
 

Comment