KatInterview

Enumerate Every Factor of a Large Integer in Sorted Order

Math & Bit ManipulationAuto-graded · 24 test cases
MediumAuto-gradedMath & Bit Manipulationnumber-theorydivisorsfactorization

Last updated

Produce all positive factors of an integer up to 10^12 in increasing order, handling perfect squares and large primes, and consider approaches faster than a square-root scan.

Enumerate Every Factor of a Large Integer in Sorted Order

You are given a positive integer num. Return a list containing every positive integer that divides num with no remainder, sorted from smallest to largest.

A positive integer d is a factor of num exactly when num % d == 0.

Requirements

  • Each factor must appear exactly once in the result, so the list is strictly increasing.
  • The first element is always 1 and the last element is always num.
  • Perfect squares need care: the square root is its own partner and must not be listed twice.

Extension (optional thinking)

A straightforward scan up to the square root of num is enough to pass, but consider whether you can do better asymptotically, for example by working from the prime factorization of num. Note that the output itself has a size that cannot be avoided.

Constraints

  • 1 <= num <= 10^12
  • num may be larger than 2^31 - 1, so be careful with fixed-width integer types in other languages.
  • All intermediate values fit comfortably within 64-bit integers.

Examples

Example 1

Input: list_factors(36)

Output: [1, 2, 3, 4, 6, 9, 12, 18, 36]

Example 2

Input: list_factors(97)

Output: [1, 97]

Example 3

Input: list_factors(1)

Output: [1]

Hints

Hint 1

Factors pair up: if d divides num, so does num // d. One factor in every pair is at most the integer square root of num, so you only need to scan that far.

Hint 2

When d * d == num, the two partners coincide. Add that value just once, and prefer integer square root over floating-point sqrt to avoid rounding errors.

Hint 3

For something faster than a square-root scan, find the prime factorization num = p1^e1 * ... * pk^ek. Every factor is a choice of exponent between 0 and ei for each prime, so build them by multiplying out and then sort. Primality testing (Miller-Rabin) and Pollard's rho make the factoring step fast.