Program to find number of pairs between x, whose multiplication is x and they are coprime in Python


Suppose there is a function f(x), that counts number of (p, q) pairs, such that

  • 1 < p <= q <= x
  • p and q are coprime
  • p * q = x So if we have n.

We have to find sum f(x[i]) for all i in range 1 to n.

So, if the input is like 12, then the output will be 3, because x values are ranging from 1 to 12.

  • When x = 6, the valid pair is (2, 3) so f(6) = 1
  • When x = 10, the valid pair is (2, 5) so f(10) = 1
  • When x = 12, the valid pair is (3, 4) so f(12) = 1

so there are total 3 pairs.

To solve this, we will follow these steps −

  • count := 0
  • sqr := integer part of (square root of n) + 1
  • for base in range 2 to sqr - 1, do
    • for i in range 1 to minimum of base and floor of (n / base - base + 1), do
      • if gcd of base and i) is not same as 1, then
        • go for next iteration
      • count := count + floor of (n - i * base)/(base * base)
  • return count

Example

Let us see the following implementation to get better understanding −

from math import sqrt, gcd

def solve(n):
   count = 0
   sqr = int(sqrt(n)) + 1
   for base in range(2, sqr):
      for i in range(1, min(base, n // base - base + 1)):
         if gcd(base, i) != 1:
            continue
         count += (n - i * base) // (base * base)

   return count

n = 12
print(solve(n))

Input

12

Output

3

Updated on: 23-Oct-2021

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements