Programming Example
Java Program - Sieve of Eratosthenes
An efficient algorithm to find all prime numbers up to a specified integer.
An efficient algorithm to find all prime numbers up to a specified integer.
import java.util.Arrays;
public class SieveOfEratosthenes {
public static void main(String[] args) {
int n = 50;
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i)
prime[j] = false;
}
}
for (int i = 2; i <= n; i++) {
if (prime[i])
System.out.print(i + " ");
}
}
}
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.