AlgoTales · Roadmap

Prime numbers

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A prime is a number greater than 1 that can only be divided evenly by 1 and itself, like 13. Primes are the building blocks of every other number, and because multiplying big primes is easy while splitting the result back is brutally hard, they protect online payments and logins.

Practical use cases

  • Web app: Safe payment pages. When a customer pays on a shop checkout, the browser and server agree on a secret using two huge prime numbers. Multiplying them is instant, but a thief who sees only the product cannot realistically work out the two primes. That one-way difficulty is what keeps the connection private.
  • Web app: Picking a good hash table size. A custom cache in your app files items into a fixed number of slots. If the slot count is a prime like 101 instead of 100, keys that follow patterns, such as ids ending in 00, spread out instead of piling into a few slots. Lookups stay quick and the cache is evenly used.
  • System: Random number and key generators. Security software needs to check whether a freshly generated big number is prime before using it as part of a key. It tests candidates quickly by trying small divisors up to the square root, then stronger tests for larger ones.

The story: The Stubborn Chocolates

At Mira's birthday, Mrs. Sharma gave her a packet of chocolates to arrange in neat rectangles on a plate. "12 chocolates? Easy: 2 rows of 6, or 3 rows of 4, or 4 rows of 3." Everything arranged beautifully. Then came the packet with 13. Two rows? One left over. Three rows? One left over. The only neat arrangement was a single long line.

"Some numbers are stubborn," said Mrs. Sharma. "They refuse to break into smaller equal groups. 2, 3, 5, 7, 11, 13... we call them prime numbers. Everything else is a composite, because it can be built by multiplying smaller numbers." Kabir noted that 1 does not count: a prime must have exactly two divisors, 1 and itself.

Now Kabir wanted to test 29. He tried 2, 3, 4, 5 ... Mira stopped him at 5. "Pairs! Every way to break a number is a pair, like 7 × 13 for 91. One partner is small and the other is big. If a small partner existed, you would find it before you pass the middle, which is where a number times itself would overtake 29." So you only ever try divisors while d × d is not more than the number.

Primes look like a small curiosity, but they are the building blocks of every whole number, and they guard your bank passwords. Now you can test any number in seconds.

How to spot this problem, and where you need it

You need numbers that do not split evenly, to spread data without patterns or protect secrets, or the task asks whether a number is prime or what its factors are.

Signs you need it

  • The problem asks whether a number is prime, lists primes up to a limit, or breaks a number into its prime factors.
  • Keys, ids or timestamps with a pattern are landing in the same few buckets of a hash table or shard.
  • You are reading about RSA, key exchange or secure random generation and see the words large primes.

Where to use it in a project

  • Choosing the number of buckets in a custom hash table or the modulus for a simple hashing function.
  • Understanding and configuring security features such as HTTPS, key generation and signed tokens.

The solution

To test one number, divide it only by numbers up to its square root: if none divides evenly, it is prime. This stops long before the number itself, so even a 10-digit value needs about 100,000 tries at most, not 10 billion. Skip even numbers after 2 to halve the work again. For many numbers at once, use a sieve instead.

Payoff: Before: testing 1,000,000,007 by trying every smaller number takes a billion checks. After: about 31,600 checks, finishing in milliseconds.

Explain it like I am 8

A prime is a number of sweets that you cannot lay out in an even rectangle, except one long line. 12 sweets can make a rectangle but 13 cannot. And to check, you only need to try small groups, because big groups always come with a small partner.

How it works, step by step

  1. Rule out the small cases: numbers below 2 are not prime, and 2 is the only even prime.
  2. Try dividers d = 2, 3, 4, ... and check if n % d === 0.
  3. Stop early when d * d > n, because every factor pair has one small member.
  4. If any d divides n, it is composite. If none do, it is prime.
  5. Need many primes? A sieve (next lesson) finds all primes up to a limit much faster than testing one by one.

The code in four languages

PHP

<?php
// Is $n prime? Try divisors only while d * d <= n.
function isPrime(int $n): bool {
    if ($n < 2) return false;           // 0 and 1 are not prime
    if ($n % 2 === 0) return $n === 2;  // 2 is the only even prime
    for ($d = 3; $d * $d <= $n; $d += 2) {   // odd divisors only
        if ($n % $d === 0) return false;
    }
    return true;
}

$primes = [];
for ($i = 1; $i <= 50; $i++) {
    if (isPrime($i)) $primes[] = $i;
}
echo "Primes up to 50: " . implode(', ', $primes) . "
";
echo "29 prime? " . (isPrime(29) ? 'yes' : 'no') . "
";
echo "91 prime? " . (isPrime(91) ? 'yes' : 'no') . "
";   // 7 x 13
echo "1000003 prime? " . (isPrime(1000003) ? 'yes' : 'no') . "
";

JavaScript

// Is n prime? Try divisors only while d * d <= n.
function isPrime(n) {
  if (n < 2) return false;            // 0 and 1 are not prime
  if (n % 2 === 0) return n === 2;    // 2 is the only even prime
  for (let d = 3; d * d <= n; d += 2) {    // odd divisors only
    if (n % d === 0) return false;
  }
  return true;
}

const primes = [];
for (let i = 1; i <= 50; i++) {
  if (isPrime(i)) primes.push(i);
}
console.log("Primes up to 50: " + primes.join(', '));
console.log("29 prime? " + (isPrime(29) ? 'yes' : 'no'));
console.log("91 prime? " + (isPrime(91) ? 'yes' : 'no'));    // 7 x 13
console.log("1000003 prime? " + (isPrime(1000003) ? 'yes' : 'no'));

Java

import java.util.*;

public class Main {
    // Is n prime? Try divisors only while d * d <= n.
    static boolean isPrime(int n) {
        if (n < 2) return false;           // 0 and 1 are not prime
        if (n % 2 == 0) return n == 2;     // 2 is the only even prime
        for (int d = 3; (long) d * d <= n; d += 2) {   // odd divisors only
            if (n % d == 0) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        List<Integer> primes = new ArrayList<>();
        for (int i = 1; i <= 50; i++) {
            if (isPrime(i)) primes.add(i);
        }
        System.out.println("Primes up to 50: " + primes.toString().replaceAll("[\\[\\]]", ""));
        System.out.println("29 prime? " + (isPrime(29) ? "yes" : "no"));
        System.out.println("91 prime? " + (isPrime(91) ? "yes" : "no"));    // 7 x 13
        System.out.println("1000003 prime? " + (isPrime(1000003) ? "yes" : "no"));
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// isPrime: try divisors only while d * d <= n.
func isPrime(n int) bool {
	if n < 2 {
		return false // 0 and 1 are not prime
	}
	if n%2 == 0 {
		return n == 2 // 2 is the only even prime
	}
	for d := 3; d*d <= n; d += 2 { // odd divisors only
		if n%d == 0 {
			return false
		}
	}
	return true
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	var primes []string
	for i := 1; i <= 50; i++ {
		if isPrime(i) {
			primes = append(primes, strconv.Itoa(i))
		}
	}
	fmt.Println("Primes up to 50:", strings.Join(primes, ", "))
	fmt.Println("29 prime?", yesNo(isPrime(29)))
	fmt.Println("91 prime?", yesNo(isPrime(91))) // 7 x 13
	fmt.Println("1000003 prime?", yesNo(isPrime(1000003)))
}

Time: O(√n) per test · Extra space: O(1). You only try divisors up to the square root of n, so even a number with ten digits needs just a few hundred thousand checks.

Watch out for

  • Calling 1 a prime. A prime needs exactly two divisors; 1 has only one.
  • Testing every number up to n (or n/2) when going up to the square root is enough.
  • Forgetting that 2 is prime (and the only even one), so an "all evens are not prime" shortcut must keep 2.

Quick check

  1. Which of these is prime?
    • 21
    • 27
    • 23
  2. Why can we stop testing divisors once d × d is bigger than n?
    • Because factors come in pairs, and the small one would already have been found
    • Because computers are fast
    • Because primes are rare
  3. Is 1 a prime number?
    • Yes
    • No, it has only one divisor
    • Only sometimes