Count all pairs of divisors of a number N whose sum is coprime with N
Last Updated :
20 Apr, 2023
Given an integer N, the task is to count all pairs of divisors of N such that the sum of each pair is coprime with N.
Examples:
Input: N = 24
Output: 2
Explanation:
There are 2 pairs (1, 24) and (2, 3) whose sum is coprime with 24
Input: 105
Output: 4
Explanation:
There are 4 pairs (1, 105), (3, 35), (5, 21) and (7, 15) whose sum is coprime with 105
Approach:
To solve the problem mentioned above we can easily calculate the result by finding all divisors in ?N complexity, and check for each pair, whether its sum is coprime with N or not.’
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int gcd( int a, int b)
{
if (b == 0)
return a;
return (gcd(b, a % b));
}
int CountPairs( int n)
{
int cnt = 0;
for ( int i = 1; i * i <= n; i++) {
if (n % i == 0) {
int div1 = i;
int div2 = n / i;
int sum = div1 + div2;
if (gcd(sum, n) == 1)
cnt += 1;
}
}
return cnt;
}
int main()
{
int n = 24;
cout << CountPairs(n) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
public static int gcd( int a, int b)
{
if (b == 0 )
return a;
return (gcd(b, a % b));
}
public static int CountPairs( int n)
{
int cnt = 0 ;
for ( int i = 1 ; i * i <= n; i++)
{
if (n % i == 0 )
{
int div1 = i;
int div2 = n / i;
int sum = div1 + div2;
if (gcd(sum, n) == 1 )
cnt += 1 ;
}
}
return cnt;
}
public static void main(String[] args)
{
int n = 24 ;
System.out.println(CountPairs(n));
}
}
|
Python3
import math as m
def CountPairs(n):
cnt = 0
i = 1
while i * i < = n :
if (n % i = = 0 ):
div1 = i
div2 = n / / i
sum = div1 + div2;
if ( m.gcd( sum , n) = = 1 ):
cnt + = 1
i + = 1
return cnt
n = 24
print (CountPairs(n))
|
C#
using System;
class GFG {
static int gcd( int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int CountPairs( int n)
{
int cnt = 0;
for ( int i = 1; i * i <= n; i++) {
if (n % i == 0) {
int div1 = i;
int div2 = n / i;
int sum = div1 + div2;
if (gcd(sum, n) == 1)
cnt += 1;
}
}
return cnt;
}
public static void Main()
{
int n = 24;
Console.WriteLine(CountPairs(n));
}
}
|
Javascript
<script>
function gcd(a, b)
{
if (b == 0)
return a;
return (gcd(b, a % b));
}
function CountPairs(n)
{
let cnt = 0;
for (let i = 1; i * i <= n; i++) {
if (n % i == 0) {
let div1 = i;
let div2 = Math.floor(n / i);
let sum = div1 + div2;
if (gcd(sum, n) == 1)
cnt += 1;
}
}
return cnt;
}
let n = 24;
document.write(CountPairs(n) + "<br>" );
</script>
|
Time Complexity: O(?N * log(N))
Auxiliary Space: O(log(min(a,b)) for call stack
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...