← Questions

Count pairs with 1/x + 1/y = 1/N

0
MicrosoftCodingLast asked Nov 2025

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 N per call, or many queries?

What a strong answer covers

  • The algebra: both x and y exceed N; write x = N + a, y = N + b; the equation becomes a * b = N^2.
  • So every positive divisor a of N^2 gives exactly one ordered pair, and the answer is the number of divisors of N^2.
  • Factor N = p1^e1 * ... * pk^ek by trial division up to sqrt(N); the count is the product of (2*ei + 1). O(sqrt(N)) time.
  • Why brute force over x is too slow: x can be as large as N^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

What it tests

number theory · math

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