Given a positive integer N, the task is to find the number of positive integers whose GCD with the given integer N is the number itself.
Input: N = 5
Following are the numbers whose GCD with N is the number itself:
- Number 1: GCD(1, 5) = 1.
- Number 1: GCD(5, 5) = 5.
Therefore, the total count is 2.
Input: N = 10
Approach: The given problem can be solved based on the observation that the necessary condition for GCD of any number(say K) with N is K if and only if K is a factor of N. Therefore, the idea is to find the number of factors of N. Follow the below steps to solve the problem:
- Initialize a variable, say count as 0, to count the number of factors of N.
- Iterate over the range [1, sqrt(N)] and perform the following steps:
- If the current number i divides the given integer N, then increment count by 1.
- If the value of i and N / i is not the same, then increment count by 1.
- After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:
Time Complexity: O(N1/2)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.