Skip to main content
Beginnercoding Verified

Find all factors of a given number efficiently.

ReportedSource: GeeksforGeeks interview experience: LinkedIn, experienced

Quick answer

Test divisors d up to sqrt(n); add d and n/d (once if equal); collect small ascending and large descending. O(sqrt n). Or prime-factorise and combine exponents.

Constraints

  • Input: one line with the integer n.
  • Output: all positive divisors of n in ascending order, separated by single spaces, on one line.
  • 1 <= n <= 10^12 (a loop up to sqrt(n) must be fast enough).
  • Use 64-bit integers in Java.

Sample I/O

in: 12

out: 1 2 3 4 6 12

in: 36

out: 1 2 3 4 6 9 12 18 36

in: 13

out: 1 13

Loading editor…
Output

Sign up to run your code in the sandbox.

Sign up to run code and get an AI review

You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.

Sign up free

Hints

Reference solution

Trial division up to sqrt(n). Factors come in pairs (d, n // d), so you only need to test d up to sqrt(n).

main.py
def factors(n):
    small, large = [], []
    d = 1
    while d * d <= n:
        if n % d == 0:
            small.append(d)
            if d != n // d:
                large.append(n // d)
        d += 1
    return small + large[::-1]   # sorted

Complexity. O(sqrt(n)) time. The d != n // d check avoids listing the square root twice for perfect squares.

Prime factorisation route (what the candidate used). Factorise n = p1^a1 · p2^a2 ..., then generate every factor recursively by choosing an exponent 0..ai for each prime. Useful when you need factors of many numbers (precompute smallest prime factors with a sieve) or only the count: (a1+1)(a2+1)....

Edge cases. n = 1, n prime, negative input, very large n (mention Pollard's rho only if asked).

Discussion