adisharma asked 2 years ago

Hello All, I working on a java project and I am confused sieve of eratosthenes coding problem. The problem statement is Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. I am trying to solve this problem by Efficient Approach

A prime number is a number that is divisible by only two numbers – themselves and 1

Example:

Input: n =10

Output: 2 3 5 7

I have checked sieve of eratosthenes coding problem on google and I have found this problem post https://www.interviewbit.com/blog/sieve-of-eratosthenes/ I am sharing one code example. Can anyone explain me, how sieve of eratosthenes program works? or explain with another example?

class SieveOfEratosthenes { void sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++){ if (prime[p] == true) { for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++) { if (prime[i] == true) System.out.print(i + " "); } } }

1 Answers

Rehmaanali Staff answered 2 years ago

The basic idea: a prime number is divisible only by itself and 1, and 1 itself isn’t a prime number. So the first prime number is 2. To identify prime numbers, start with 2, add that to a list of prime numbers, strike out all multiples of 2 (because they are all divisible by 2 so they are not prime), and increment the number counter.

Repeat the same process described above for each new number between 2 and some selected highest number. Compare each new number to the list of struck-out (i.e. composite) numbers and skip those numbers. At the end of the process, any number not struck out is prime.

By detecting and skipping the struck-out numbers from the list and only listing numbers that were not already struck out, this simple algorithm detects prime numbers within a specified range.

For a given highest number, a significant speed-up test only numbers between 2 and the square root of the highest number. Here is an example I just wrote:

```
public class Eratosthenes {
public static void main(String[] args) {
int highest = 100;
// boolean array default value is false
boolean[] composite = new boolean[highest];
// test numbers between 2 and sqrt(highest)
for (int n = 2;n*n < highest;n += 1) {
// if n is prime
if (!composite[n]) {
// mark all multiples of n as composite
for (int m = n+n; m < highest;m += n) {
composite[m] = true;
}
}
}
// display results
for (int n = 2;n < highest;n += 1) {
// if n is prime
if (!composite[n]) {
System.out.printf("%3d is prime.\n",n);
}
}
} // end of function main
} // end of class Eratosthenes
```