3) Implement the Sieve of Eratosthenes in a method: boolean [] sieve(int n) siev
ID: 3711696 • Letter: 3
Question
3) Implement the Sieve of Eratosthenes in a method:
boolean [] sieve(int n)
sieve() returns an array of n + 1 booleans (0 - n, inclusive) where index
i of the array is true if and only if i is prime.
You may not use isPrime(), and nor may your isPrime() solution use output
from sieve().
For instance, sieve(12) returns an array containing the values:
false false true true false true false true false false false true
corresproding with the integers
0 1 2 3 4 5 6 7 8 9 10 11
Explanation / Answer
class Main {
//taking 1 parameter
static boolean isPrime(int n){
if(n==0 || n==1)
return false;
// if there is any number for which n is divisible between 2 and n-1,returning false
for(int 1=2;i<n;i++)
{
if(n%i== 0)
return false;
}
//otherwise the control comes here and returns true
return true;
}
Static boolean [] sieve(int n)
{
boolean[] result = new boolean[n];
//looping from 0 to n-1 and taking result into result which is boolean array
for(int 1=0;i<n;i++)
{
result[i] = isPrime(i);
}
return result;
}
public static void main (String[] args) {
boolean[] there = sieve(12);
for(int i=0;i<12;i++)
{
System.out.print(there[i] +" ");
}
}
}
/*SAMPLE OUTPUT
false false true true false true false true false false false true
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.