Java

ggg

Joined
Jan 18, 2022
Messages
1
Reaction score
0
Hi ppl I need a help with some little task,any code change help will be aprreciatate!
so my task is bassicaly:
Given a positive number n, make a boolean array and
execute the sieve algorithm for an array of size
n+1.
You can initialize the values of array[0] and array[1] to be
false, then you should print all the prime numbers using the
array(meaning the cells which are set to true should imply that
the cell number is prime)
For example:
if n is 10, the array should be
[false,false,true,true,false,true,false,true,false,false,false]
and the output should be “2, 3, 5, 7”.
My code is:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
boolean[] bool = new boolean[num];

for (int i = 0; i< bool.length; i++) {
bool = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
System.out.println("List of prime numbers upto given number are : ");
for (int i = 2; i< bool.length; i++) {
if(bool==true) {
System.out.println(i);
 
Joined
Mar 3, 2021
Messages
241
Reaction score
30
You're actually _really_ close. When you compile your code, it points out the few places that you used bool instead of bool[i]: in your first loop setting them all to true, then the two times you're comparing bool to true in your other loops. Just change those and you're golden.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top