Hi 👋, I'm a software engineer specializing in backend systems, distributed systems, and scalable architecture. My blog shares practical tutorials based on 3+ years of experience. LeetCode 1756 (Top 10%). Actively seeking SDE roles — let's get in touch!
Comments
Leave a Comment
Success!
Receive Latest Updates 📬
Get every new post, special offers, and more via email. No fee required.
In this tutorial, I will show you how to check if a number is a prime number in Python using 4 different algorithms from easy to advanced.
The naive solution to check if a number is a prime number is to count the number of divisors.
First, let's remind of the definition of a prime number. Prime numbers are numbers:
greater than 1
divisible by 1 and itself only, in other words, it has exactly two divisors.
For example, 2, 3, 5, 7, 11, etc. are prime numbers.
Based on this observation, we can write a naive algorithm to check if it has exactly two divisors or not.
check-prime-number-naive.py
def is_prime(n): if n <= 1: return False divisor_count = 0 for i in range(1, n + 1): if n % i == 0: divisor_count += 1 return divisor_count == 2print(is_prime(2)) # Trueprint(is_prime(3)) # Trueprint(is_prime(4)) # Falseprint(is_prime(5)) # True
The Sieve of Eratosthenes is an algorithm that can precompute all the prime numbers from 1 to n in O(n * log(log(n))) time complexity.
So, the next time someone give you a bunch of m questions asking you to check if a number is a prime number, you can answer each question in O(1) time complexity.
In general, the Sieve of Eratosthenes is an algorithm that filters out all the composite numbers from 1 to n, giving us all the prime numbers from 1 to n. See the visualization below.
As you can see, it filters out the numbers you clicked, and the remaining numbers are prime numbers from 1 to 100. That's basically how the Sieve of Eratosthenes works.
I have made the visualizer for the Sieve of Eratosthenes algorithm. Now let's turn it into a explicit algorithm.
Comments