← Questions
Count pairs with 1/x + 1/y = 1/N
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Microsoft's HackerRank assessment, last asked Nov 2025. It tests number theory and math.
Given a positive integer N, count the ordered pairs of positive integers (x, y) with 1/x + 1/y = 1/N. Pairs (x, y) and (y, x) count separately when x != y.
Interface
Unless you agree on a different interface with the interviewer, assume:
count_pairs(n: int) -> int
Example
1 -> 1 # (2, 2)
2 -> 3 # (3, 6), (4, 4), (6, 3)
4 -> 5
6 -> 9 # 36 has 9 divisors
Constraints
-
1 <= N <= 10^6.
Clarifying questions
- Ordered pairs, so
(3, 6)and(6, 3)are two answers? - Only positive integers, no zero or negatives?
- One
Nper call, or many queries?
What a strong answer covers
- The algebra: both
xandyexceedN; writex = N + a,y = N + b; the equation becomesa * b = N^2. - So every positive divisor
aofN^2gives exactly one ordered pair, and the answer is the number of divisors ofN^2. - Factor
N = p1^e1 * ... * pk^ekby trial division up tosqrt(N); the count is the product of(2*ei + 1). O(sqrt(N)) time. - Why brute force over
xis too slow:xcan be as large asN^2 + N. - Checking the formula against a brute force for small
N.
Follow-ups
- Answer 10^5 queries for different
N: precompute smallest prime factors with a sieve. - Count unordered pairs instead.
- List the pairs themselves, in increasing order of
x.
Where it's asked
- Microsoft · HackerRank assessment · Last asked Nov 202590 min · Two problems in a locked full-screen browser
What it tests
number theory · math
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
