Divisors and primes in O(√n)

Open on YouTube

1 Trying every number is too slow

A divisor of n is a number that divides n with no remainder. In code, i is a divisor of n when n % i == 0. So 4 is a divisor of 36, and 5 is not.

Our running problem counts the divisors of n. For n = 36 they are 1, 2, 3, 4, 6, 9, 12, 18 and 36, so the answer is 9.

The first idea tries every i from 1 to n and counts the ones that divide n. It is correct, and for 36 it does 36 checks. But problems in this part of the roadmap allow n up to 10⁹ and beyond. At n = 10⁹ that is 10⁹ checks. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).

This lesson cuts the work to about 3 × 10⁴ checks for the same n.

2 Divisors come in pairs

When i divides n, the result n / i divides n too, because the two multiply back to n. We call n / i the partner of i. For 36 the pairs are:

1 × 36, 2 × 18, 3 × 12, 4 × 9, 6 × 6

The smaller numbers are 1, 2, 3, 4 and 6. None of them is above 6, and 6 is √36. On a number line, the small numbers sit on the left of √36, the partners sit on the right, and the pair 6 × 6 sits on √36 itself.

smaller, up to √36partners, 36 / i0√3636123469121836
The nine divisors of 36: each one on the left pairs with one on the right

This holds for every n, and the reason is short:

  1. Take any pair, i × (n / i) = n.
  2. If both numbers were bigger than √n, their product would be bigger than √n × √n, which is n.
  3. But their product is exactly n. So at least one of the two is at most √n.

So we never need to try an i above √n. Every i from 1 up to √n that divides n gives us two divisors at once: i and its partner n / i.

3 Counting the divisors of 36

We try i = 1, 2, 3, … and stop once i * i is bigger than n. Each time n % i is 0, we add 1 for i and 1 for its partner. A trace for n = 36:

ii * i36 % ipartnercount
110362
240184
390126
416098
5251—8
636069
749stop

The loop runs six times instead of 36 and returns 9.

The last row with a divisor needs care. At i = 6, the partner is 6 again, so it is one divisor, not two. This happens only when n is a perfect square, a number like 36 or 49 that is some whole number times itself. So we add the partner only when it differs from i. A number that is not a square, such as 35 = 5 × 7, never meets this case.

The code returns 9 for 36, 4 for 35 and 1 for 1.

4 What we save

The loop runs about √n times, with one remainder check each time. So the time is O(√n). It keeps only i, partner and count, so the extra space is O(1).

At n = 10⁹, √n is about 3 × 10⁴, so the loop does about 3 × 10⁴ checks. Trying every number does 10⁹.

O(n), 10⁹10⁹O(√n), 10⁹3.2 × 10⁴O(√n), 10¹⁰10⁵about 1 second
Checks at n = 10⁹ and n = 10¹⁰, on a scale where each mark is ten times the last

Even at n = 10¹⁰, the √n loop does about 10⁵ checks and finishes far inside the limit.

5 Writing the stop check

There are three ways to write "stop after √n". Only one is safe everywhere.

  • i * i <= n. This uses whole numbers only, so it is exact. It is the form we use.
  • i <= sqrt(n). sqrt works with decimal numbers, and those are rounded. For very large n, the result can come out one off, and the loop then misses its last i or tries one too many. It also calculates a square root on every check.
  • i * i <= n with a 32-bit i. i * i is calculated in the type of i. For n = 2,147,483,647, the largest int, i reaches 46,341, and i * i goes past the int range. The product wraps around to a wrong value that is still below n, so the loop runs far past √n and gets TLE.

The fix for the last one is a 64-bit i, as in the code above. Another fix is to divide instead of multiply: i <= n / i cannot overflow.

6 Checking for a prime

A prime is a number greater than 1 whose only divisors are 1 and itself. So 2, 3, 5, 7 and 97 are prime, and 36 is not. 1 is not prime. It has only one divisor.

To check n, we look for a divisor between 2 and √n. If n is not prime, it has a pair i × (n / i) with neither number equal to 1 or n. The smaller one of that pair is at least 2 and at most √n, so the loop finds it. If no i in that range divides n, n is prime.

isPrime(n)
    if n < 2
        return false
    i = 2
    while i * i <= n
        if n % i == 0
            return false
        i = i + 1
    return true

Two runs show both ends:

  • n = 97. The loop tries 2 to 9, since 10 × 10 = 100 is past 97. None divides 97, so it returns true.
  • n = 49. The loop tries 2 to 6 with no luck. At i = 7, 7 * 7 = 49 is still allowed, and 49 % 7 is 0, so it returns false.

The check stops at the first divisor it finds. So a number that is not prime usually finishes fast, and a prime does the full √n checks. The worst case is a large prime, still O(√n).

7 Mistakes and their inputs

Each of these passes some examples and fails on one input.

  • The square root counted twice. Adding 2 for every divisor i gives 10 for n = 36, because 6 is counted as its own partner. For n = 1 it gives 2.
  • < instead of <=. With i * i < n, the loop stops before i = 6 and returns 8 for 36. The same slip makes the prime check say 49 is prime, because it never tries 7.
  • Forgetting that 1 is not prime. Without the n < 2 check, the loop for n = 1 never runs, and the function returns true.
  • Starting the prime loop at 1. Every number divides by 1, so the function returns false for every n, even 97.

8 When to use it

The signal is a single number as input and a question about what divides it. Some forms it takes:

  • List the divisors. The same loop finds them all. The small ones come out in increasing order and their partners in decreasing order, so the list needs one more step to come out sorted.
  • Add up the divisors. Perfect Number asks for the sum of n's divisors other than n. The pairs give that sum in O(√n) too.
  • Is n prime? The check above, with 1 handled first.

The next lesson finds the largest divisor that two numbers share, without listing any divisors. When a problem asks for every prime up to a large limit, checking each number one by one gets slow, and a later lesson on the sieve handles that.

The habit to keep: when a loop looks for divisors of n, stop at i * i <= n with a 64-bit i, take the partner n / i with it, and count it once when it equals i.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.