Problem Statement
Given two positive integers x and y, representing the GCD and LCM of two unknown positive integers a and b, find the number of valid ordered pairs (a, b).
The pair (a, b) and (b, a) are considered different when a != b.
Example
Input:
x = 2
y = 12
Output:
4
The valid pairs are:
(2, 12)
(4, 6)
(6, 4)
(12, 2)
All these pairs have:
GCD = 2
LCM = 12
Approach
We use the important mathematical property:
a × b = GCD(a, b) × LCM(a, b)
Since:
GCD(a, b) = x
LCM(a, b) = y
we get:
a × b = x × y
Because the GCD of a and b is x, we can write:
a = x × p
b = x × q
where p and q are coprime.
Substituting into the product equation:
(x × p) × (x × q) = x × y
After simplifying:
p × q = y / x
Therefore, the first thing we need to check is whether y is divisible by x.
If:
y % x != 0
then no valid pair exists.
Counting the Pairs
Let:
n = y / x
We need to divide the prime factors of n between p and q.
For every distinct prime factor, there are two choices:
Put the prime factor in
p.Put the prime factor in
q.
If n has k distinct prime factors, the number of ordered pairs is:
2^k
Example
For:
x = 2
y = 12
we get:
n = 12 / 2
= 6
Prime factorization:
6 = 2 × 3
There are two distinct prime factors: 2 and 3.
Therefore:
answer = 2^2
= 4
The four possibilities correspond to:
p = 1, q = 6 → (a, b) = (2, 12)
p = 2, q = 3 → (a, b) = (4, 6)
p = 3, q = 2 → (a, b) = (6, 4)
p = 6, q = 1 → (a, b) = (12, 2)
Java Code
class Solution {
public int pairCount(int x, int y) {
// LCM must be divisible by GCD
if (y % x != 0) {
return 0;
}
int n = y / x;
int distinctPrimeFactors = 0;
// Find distinct prime factors of n
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
distinctPrimeFactors++;
// Remove all occurrences of this prime factor
while (n % i == 0) {
n /= i;
}
}
}
// If one prime factor remains
if (n > 1) {
distinctPrimeFactors++;
}
// Number of ordered pairs = 2^k
return 1 << distinctPrimeFactors;
}
}
Code Explanation
1. Check Whether LCM Is Divisible by GCD
if (y % x != 0) {
return 0;
}
The LCM of two numbers is always divisible by their GCD.

Join the conversation! Your thoughts help the community grow.