Reputation: 1
I am trying to do the Sieve of Eratosthenes using a for loop then an if statement by checking for prime numbers up to 30 however I have a problem. Because of my code 2,3 and 5 are all shown as not prime numbers because they are divisible by 2,3 and 5 of course. How do I edit my code to make these come up as prime numbers?
Here is my code
public class prime {
public static void main(String[] args) {
for(int a=2; a<=30; a++){
if(a%2 == 0 || a%3 == 0 || a%5 == 0){
System.out.println(a +" = Not Prime");
}
else
{
System.out.println(a + " = Prime");
}
}
}
}
Thanks
Upvotes: 0
Views: 187
Reputation: 1
Thanks for the help, I added some code in in the if statement to check if its 2, 3 or 5.
public class prime {
public static void main(String[] args) {
for(int a=2; a<=30; a++){
if(**a != 2** && a%2 == 0 ||**a !=3** && a%3 == 0 ||**a != 5** && a%5 == 0){
System.out.println(a +" = Not Prime");
}
else
{
System.out.println(a + " = Prime");
}
}
}
}
Upvotes: 0
Reputation: 717
The definition of a prime is that it is not divisible by another natural number other than 1
or itself. So, you need to devise a test for this, e.g., a != 2
, etc., or, a / 2 != 1
. In your code:
if (a != 2 && a % 2 == 0 || ...
Upvotes: 0
Reputation: 49803
Add an if
statement to explicitly test for a
being 2,3 or 5 before you test for divisibility.
Upvotes: 1