I need to write a code in java based on an alrgorithm, the alrgorithm and it’s problem are below:
The Sieve of Eratosthenes is “a simple, ancient algorithm for finding all prime numbers up to any given limit,” which you can read about at: (Wikipedia: Sieve of Eratosthenes)
Write a method called sieve that takes an integer parameter, n , and returns a boolean array that indicates, for each number from 0 to n – 1, whether the number is prime.
3 answers
I just need some help on how to set this up
Not sure what boolean array is or what to put in it, but I assume you put either true/false for a number at the corresponding index, depending on if its prime or not.
(This is pseudocode so you get an idea of what to do.)
boolean[] sieve(int n) {
// you should make a for loop here that loops from n to 0 to check if
n mod 2.
for (int i = n; i > n; i--) { // something like this. you can go n -> 0 or 0 -> n
// inside the for loop you could have an if loop to check if n mod 2 is
true.
if (n mod 2 == true)
//take index i and put false inside, since n is not a prime.
else
//n is a prime. at that index, you'd put true.
}
//after the loop is terminated return the boolean array
}
I hope this helps?
(This is pseudocode so you get an idea of what to do.)
boolean[] sieve(int n) {
// you should make a for loop here that loops from n to 0 to check if
n mod 2.
for (int i = n; i > n; i--) { // something like this. you can go n -> 0 or 0 -> n
// inside the for loop you could have an if loop to check if n mod 2 is
true.
if (n mod 2 == true)
//take index i and put false inside, since n is not a prime.
else
//n is a prime. at that index, you'd put true.
}
//after the loop is terminated return the boolean array
}
I hope this helps?
thank you, it did