Check if a Number is Prime or Not

Pattern: Recursion basics

easy

Test for a prime recursively, where each call tries one candidate divisor and hands the next candidate to a smaller call.

The problem

You are given a whole number n from 1 to 100,000. Return true if it is prime (at least 2, with no divisors other than 1 and itself) and false otherwise, using recursion instead of a loop. For example, 13 is prime and 49 is not.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name isPrime and the limit above are this guide's own. The loop version, and why the search can stop at the square root, is in "Check for Prime Number" in Maths basics.

Think first

  • In the loop version, what changes from one round to the next? That changing value becomes the extra parameter.
  • When should the recursion stop with "prime"? When should it stop with "not prime"?
  • How deep does the recursion go for n = 100,000?

Hints

    Brute force, and why it fails

    The loop version is the natural answer and uses constant memory. A recursion that tries every d from 2 to n - 1 would also be correct, but it would go up to 100,000 calls deep and crash in Python. Stopping at √n keeps the depth near 316, which is safe.

    The key insight

    Any loop can be written as a recursion: the loop variable becomes a parameter, the loop's exit test becomes the base case, and "go round again" becomes a call with the next value.

    Dry run

    20d
    31 
    42 
    53 
    64 
    75 
    n49
    d2
    49 / d24
    49 % d1

    n = 49. It is at least 2, so call noDivisorFrom(49, 2). The array lists the candidates d that may be tried.

    Step 1 of 6

    The plan

    function isPrime(n):
        if n < 2:
            return false
        return noDivisorFrom(n, 2)
    
    function noDivisorFrom(n, d):
        if d > n div d:
            return true                    # passed the square root
        if n mod d == 0:
            return false                   # found a divisor
        return noDivisorFrom(n, d + 1)     # try the next candidate
    

    Complexity

    Time
    O(√n)
    Space
    O(√n)

    At most about √n calls, each doing constant work. They can all be open at once, so the stack holds up to about √n frames: at most around 316 for this problem's limit.

    Edge cases

    • 1 is not prime. 2 is prime: the first call already has 2 > 2 / 2.
    • 49 = 7 × 7 shows why the test is d > n / d and not d >= n / d: at d = 7 we must still test.
    • 99,991 is prime and makes the deepest chain within the limit.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isPrime(int n) {
            if (n < 2) {
                return false;
            }
            return noDivisorFrom(n, 2);
        }
    
        private boolean noDivisorFrom(int n, int d) {
            if (d > n / d) {
                return true;                    // passed the square root: no divisor
            }
            if (n % d == 0) {
                return false;                   // found a divisor
            }
            return noDivisorFrom(n, d + 1);     // try the next candidate
        }
    }

    C++

    class Solution {
    public:
        bool isPrime(int n) {
            if (n < 2) {
                return false;
            }
            return noDivisorFrom(n, 2);
        }
    
        bool noDivisorFrom(int n, int d) {
            if (d > n / d) {
                return true;                    // passed the square root: no divisor
            }
            if (n % d == 0) {
                return false;                   // found a divisor
            }
            return noDivisorFrom(n, d + 1);     // try the next candidate
        }
    };

    Python

    class Solution:
        def isPrime(self, n):
            if n < 2:
                return False
            return self.noDivisorFrom(n, 2)
    
        def noDivisorFrom(self, n, d):
            if d > n // d:
                return True                         # passed the square root: no divisor
            if n % d == 0:
                return False                        # found a divisor
            return self.noDivisorFrom(n, d + 1)     # try the next candidate

    Common mistakes

    • Stopping when d == n / d instead of only when d > n / d, which calls 49 prime.
    • Forgetting to return the recursive call, so its answer is lost.
    • Recursing all the way to n - 1, which is both slow and too deep for Python.

    Similar problems