Prime Check
Basic Math
📋 Problem Statement
Given an integer , 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 has a factor , then is also a factor — so the smaller factor would already have been found. This means we only need to test divisors up to , reducing the check from to .
🔧 Approach
- Return False for (by definition, not prime).
- Return True for (only even prime).
- Return False for even .
- Loop odd divisors from 3 to (step 2).
- If any divisor evenly divides , return False.
- Otherwise return True.
⚡ Complexity Analysis
Time
— we only check up to the square root
Space
— no extra space
⚠️ Common Mistakes
- Checking all divisors instead of just up to
- Forgetting that 2 is prime and even (the only even prime)
- Using
range(2, N)instead ofrange(3, int(N**0.5)+1, 2)
🎯 Final Thoughts
The 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).