๐งฎ A Simple Sieve of Eratosthenes in Java: Find All Primes Up to N
"The prime numbers are the building blocks of all natural numbers."
โ Carl Friedrich Gauss
Prime numbers play a fundamental role in number theory and cryptography. In this post, we'll walk through the Sieve of Eratosthenes โ a simple and efficient algorithm to generate all prime numbers up to a given number n
.
We'll cover:
- โ What the sieve is
- ๐ง How it works
- ๐ง Java implementation (with fixed code)
- ๐ Real-life applications of primes
๐ What Is the Sieve of Eratosthenes?
The Sieve of Eratosthenes is a classic algorithm used to find all prime numbers less than a given integer n
. It does so by iteratively marking the multiples of each prime starting from 2.
Time Complexity: O(n log log n)
Space Complexity: O(n)
๐ก How Does It Work?
- Create a boolean array of size
n + 1
, initialized totrue
. Each index represents a number. - Starting from
2
, for each number, if it is markedtrue
, mark all its multiples asfalse
. - At the end, all indices with
true
are prime.
๐งช Java Implementation
Here's a clean and corrected version of the sieve algorithm in Java:
import java.util.Scanner; import java.util.Arrays; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); // Input the upper limit boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } } System.out.println("Prime numbers up to " + n + " are:"); for (int i = 2; i <= n; i++) { if (isPrime[i]) { System.out.print(i + " "); } } } }
๐ Fixes Made to the Original Code
- Replaced undeclared variable
num
withn
- Fixed syntax error:
===
โ==
(Java uses==
for comparison) - Included primes up to
n
(inclusive) - Set
isPrime[0]
andisPrime[1]
tofalse
explicitly - Used
Arrays.fill()
for simplicity and clarity
๐ Real-Life Applications of Prime Numbers
๐ Cryptography & Cybersecurity
Public-key encryption algorithms like RSA use large primes for secure key generation.
๐ฒ Random Number Generation
Primes are used in linear congruential generators and hash functions to produce uniform randomness.
๐ฝ Hashing Algorithms
Prime table sizes reduce hash collisions, improving performance in hash tables and bloom filters.
๐ฎ Procedural Generation in Graphics
Games use prime intervals to generate less predictable world seeds and layouts.
๐ Mathematical Research & Theories
The study of primes leads to groundbreaking theorems and conjectures (e.g., Goldbach's, Riemann Hypothesis).
๐ Try It Out Yourself
You can run the above code on any online Java compiler:
Just copy-paste the code, input a number like 100, and watch the primes roll out!
Top comments (0)