Divisors of a Number

Pattern: Maths basics

easy

List every divisor in increasing order by collecting the small half of each pair up to the square root.

The problem

You are given a whole number n from 1 up to the 32-bit limit. Return all of its divisors (the numbers that divide it exactly, including 1 and n) in increasing order. For example, the divisors of 36 are 1, 2, 3, 4, 6, 9, 12, 18 and 36.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name divisors and the limits above are this guide's own.

Think first

  • Write the divisors of 36 in pairs whose product is 36. Which pair is special?
  • In each pair, how big can the smaller number be?
  • If you collect the small numbers in increasing order, what order are their partners in?

Hints

    Brute force, and why it fails

    Try every d from 1 to n and keep the ones that divide n. The list comes out sorted for free, but it takes n steps: over 2 billion for the largest inputs, which is seconds of work for one number.

    The key insight

    Every divisor above √n is the partner of one below it. Find the small ones (about √n tries) and get the large ones for free. Because the partners appear in decreasing order, one reverse puts the whole answer in order.

    Dry run

    n36
    d1
    large[]

    n = 36. Keep two lists, small (divisors up to the square root, shown in the array) and large (their partners). Start with d = 1.

    Step 1 of 8

    The plan

    small = empty list
    large = empty list
    d = 1
    while d <= n div d:              # d * d <= n without overflow
        if n mod d == 0:
            add d to small
            if d != n div d:         # a perfect square's root is added once
                add n div d to large
        d = d + 1
    reverse large                    # partners came out largest first
    return small followed by large
    

    Complexity

    Time
    O(√n)
    Space
    O(k)

    About √n tries. k is the number of divisors returned. Even very "round" numbers below 2³¹ have only about 1,600 of them.

    Edge cases

    • n = 1 returns [1]. The only pair is (1, 1), added once.
    • A prime returns [1, n].
    • Perfect squares such as 36 or 100 list the root once.
    • 1,000,000 has 49 divisors and needs only 1,000 tries.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> divisors(int n) {
            List<Integer> small = new ArrayList<>();
            List<Integer> large = new ArrayList<>();
            for (int d = 1; d <= n / d; d++) {
                if (n % d == 0) {
                    small.add(d);
                    if (d != n / d) {
                        large.add(n / d);
                    }
                }
            }
            Collections.reverse(large);
            small.addAll(large);
            return small;
        }
    }

    C++

    class Solution {
    public:
        vector<int> divisors(int n) {
            vector<int> small;
            vector<int> large;
            for (int d = 1; d <= n / d; d++) {
                if (n % d == 0) {
                    small.push_back(d);
                    if (d != n / d) {
                        large.push_back(n / d);
                    }
                }
            }
            reverse(large.begin(), large.end());
            small.insert(small.end(), large.begin(), large.end());
            return small;
        }
    };

    Python

    class Solution:
        def divisors(self, n):
            small = []
            large = []
            d = 1
            while d <= n // d:
                if n % d == 0:
                    small.append(d)
                    if d != n // d:
                        large.append(n // d)
                d += 1
            large.reverse()
            return small + large

    Common mistakes

    • Adding a perfect square's root twice.
    • Appending the partners straight after the small divisors without reversing them, which breaks the order.
    • Writing d * d <= n in 32 bits, which overflows for inputs near the limit.
    • Sorting the result afterwards. It works, but it is extra work the reverse makes unnecessary.

    Similar problems