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 the number of (p, q) pairs such that:

  • 1 < p <= q <= x
  • p and q are coprime (their GCD is 1)
  • p * q = x

We need to find the sum f(x[i]) for all values from 1 to n.

Problem Example

If the input is 12, we examine all values from 1 to 12:

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

The total count is 3 pairs.

Algorithm

To solve this problem efficiently, we use the following approach:

  • Initialize count = 0
  • Calculate sqr = floor(?n) + 1
  • For each base from 2 to sqr-1:
  • For each multiplier i from 1 to min(base, floor(n/base) - base + 1):
  • If gcd(base, i) ? 1, skip this iteration
  • Add floor((n - i * base) / (base * base)) to count
  • Return count

Implementation

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

# Test with example
n = 12
result = solve(n)
print(f"Number of coprime pairs for n = {n}: {result}")
Number of coprime pairs for n = 12: 3

How It Works

The algorithm works by iterating through potential factor pairs systematically. For each base value, we check different multipliers and count valid combinations where:

  • The factors are coprime (gcd = 1)
  • Their product doesn't exceed our range
  • The ordering constraint p ? q is satisfied

Example Walkthrough

from math import sqrt, gcd

def solve_with_details(n):
    count = 0
    sqr = int(sqrt(n)) + 1
    valid_pairs = []
    
    for x in range(1, n + 1):
        pairs_for_x = []
        for p in range(2, x + 1):
            if x % p == 0:
                q = x // p
                if p <= q and gcd(p, q) == 1:
                    pairs_for_x.append((p, q))
        
        if pairs_for_x:
            valid_pairs.extend(pairs_for_x)
            print(f"x = {x}: {pairs_for_x}")
    
    return len(valid_pairs)

# Demonstrate with detailed output
n = 12
result = solve_with_details(n)
print(f"\nTotal coprime pairs: {result}")
x = 6: [(2, 3)]
x = 10: [(2, 5)]
x = 12: [(3, 4)]

Total coprime pairs: 3

Conclusion

This algorithm efficiently finds coprime factor pairs by leveraging mathematical properties and avoiding redundant calculations. The time complexity is optimized by limiting the search space to ?n, making it suitable for larger inputs.

Updated on: 2026-03-26T18:18:38+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements