KatInterview

Positive Divisors of N² via Prime Factorization of N

Math & Bit ManipulationAuto-graded · 23 test cases
MediumAuto-gradedMath & Bit Manipulationnumber-theorydivisorsprime-factorization

Last updated

Tests whether a candidate can reduce a unit-fraction equation to a divisor-counting problem using algebraic factoring and number theory.

Unit Fraction Pair Counter

You are given a positive integer n. Two positive integers x and y are called a matching pair for n if they satisfy:

$$\frac{1}{x} + \frac{1}{y} = \frac{1}{n}$$

Your task is to count how many ordered matching pairs (x, y) exist, where both x and y are positive integers. Order matters: (x, y) and (y, x) are counted separately when x ≠ y.

Your solution must be efficient enough to handle values as large as n = 10^6 without brute-forcing over candidate values of x or y.

Constraints

  • 1 ≤ n ≤ 10^6
  • Both x and y must be strictly positive integers.
  • Ordered pairs are counted: (x, y) and (y, x) are distinct whenever x ≠ y.
  • The answer is always a positive odd integer.

Examples

Example 1

Input: count_integer_pairs(1)

Output: 1

Example 2

Input: count_integer_pairs(2)

Output: 3

Example 3

Input: count_integer_pairs(12)

Output: 15

Hints

Hint 1

Try multiplying both sides by x·y·n to clear all three denominators, then rearrange so that one side equals zero. See if you can add a constant to both sides to make the left side factor into two binomials.

Hint 2

After factoring, you get (x − n)(y − n) = n². Convince yourself that both factors must be strictly positive. This means you are really counting the number of ways to write n² as a product of two positive integers — which is just the number of positive divisors of n².

Hint 3

You never need to compute n² explicitly. If n = p₁^e₁ · p₂^e₂ · … then d(n²) = ∏(2eᵢ + 1). Factor n by trial division up to √n in O(√n) time, accumulate the product, and handle any leftover prime greater than √n at the end.