Sieve of Eratosthenes in Java

0
31

Hello All, I am 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 to me, how sieve or 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 + " ");
		
	

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here