Algorithm LogbookAlgorithm Logbook

Prime Check

Basic Math

📋 Problem Statement

Given an integer NN, determine if it is a prime number. A prime is a number greater than 1 that has no divisors other than 1 and itself. Input: 29 → True. Input: 30 → False.

💡 Intuition

If NN has a factor f>Nf > \sqrt{N}, then N/f<NN/f < \sqrt{N} is also a factor — so the smaller factor would already have been found. This means we only need to test divisors up to N\sqrt{N}, reducing the check from O(N)O(N) to O(N)O(\sqrt{N}).

🔧 Approach

  1. Return False for N1N \leq 1 (by definition, not prime).
  2. Return True for N=2N = 2 (only even prime).
  3. Return False for even N>2N > 2.
  4. Loop odd divisors from 3 to N+1\lfloor \sqrt{N} \rfloor + 1 (step 2).
  5. If any divisor evenly divides NN, return False.
  6. Otherwise return True.

Complexity Analysis

Time

O(N)O(\sqrt{N}) — we only check up to the square root

Space

O(1)O(1) — no extra space

⚠️ Common Mistakes

  • Checking all NN divisors instead of just up to N\sqrt{N}
  • Forgetting that 2 is prime and even (the only even prime)
  • Using range(2, N) instead of range(3, int(N**0.5)+1, 2)

🎯 Final Thoughts

The N\sqrt{N} optimization is one of the most important tricks in number theory problems. This exact technique is used in the Sieve of Eratosthenes (Day 6) and prime factorization (Day 7).