[英]Sieve of Eratosthenes java prime number if statement
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. 我正在尝试使用for循环然后通过检查最多30个素数的if语句来完成Eratosthenes的筛选,但是我遇到了问题。 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. 因为我的代码2,3和5都显示为非素数,因为它们当然可以被2,3和5整除。 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 谢谢
添加if
语句明确地测试a
是2,3或5您测试整除之前。
The definition of a prime is that it is not divisible by another natural number other than 1
or itself. 质数的定义是它不能被除1
以外的其他自然数或它本身整除。 So, you need to devise a test for this, eg, a != 2
, etc., or, a / 2 != 1
. 因此,您需要为此设计一个测试,例如, a != 2
等,或者a / 2 != 1
。 In your code: 在您的代码中:
if (a != 2 && a % 2 == 0 || ...
Thanks for the help, I added some code in in the if statement to check if its 2, 3 or 5. 感谢您的帮助,我在if语句中添加了一些代码来检查其2、3或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");
}
}
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.