Count numbers having GCD with N equal to the number itself
Last Updated :
20 Jul, 2022
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.
Examples:
Input: N = 5
Output: 2
Explanation:
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
Output: 4
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:
C++
#include <bits/stdc++.h>
using namespace std;
int countNumbers( int N)
{
int count = 0;
for ( int i = 1; i * i <= N; i++) {
if (N % i == 0) {
count++;
if (N / i != i) {
count++;
}
}
}
return count;
}
int main()
{
int N = 10;
cout << countNumbers(N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
public class GFG {
static int countNumbers( int N)
{
int count = 0 ;
for ( int i = 1 ; i * i <= N; i++) {
if (N % i == 0 ) {
count++;
if (N / i != i) {
count++;
}
}
}
return count;
}
public static void main(String[] args)
{
int N = 10 ;
System.out.println(countNumbers(N));
}
}
|
Python3
def countNumbers(N):
count = 0
for i in range ( 1 , N + 1 ):
if i * i > N:
break
if (N % i = = 0 ):
count + = 1
if (N / / i ! = i):
count + = 1
return count
if __name__ = = '__main__' :
N = 10
print (countNumbers(N))
|
C#
using System;
public class GFG {
static int countNumbers( int N)
{
int count = 0;
for ( int i = 1; i * i <= N; i++) {
if (N % i == 0) {
count++;
if (N / i != i) {
count++;
}
}
}
return count;
}
public static void Main( string [] args)
{
int N = 10;
Console.WriteLine(countNumbers(N));
}
}
|
Javascript
<script>
function countNumbers(N)
{
var count = 0;
for (i = 1; i * i <= N; i++) {
if (N % i == 0) {
count++;
if (parseInt(N / i) != i) {
count++;
}
}
}
return count;
}
var N = 10;
document.write(countNumbers(N));
</script>
|
Time Complexity: O(N1/2)
Auxiliary Space: O(1), since N extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...