Java 程序列出0和n之间的所有素数,但也包括4、6和8
这是我的密码Java 程序列出0和n之间的所有素数,但也包括4、6和8,java,Java,这是我的密码 public class PrimeNumbers { private int upperLimit; public PrimeNumbers() { } public boolean isPrime(int c) { boolean x = true; for(int i = 3; i < (int)(Math.sqrt(c)) + 1; i++) { if(c % i == 0) {
public class PrimeNumbers
{
private int upperLimit;
public PrimeNumbers()
{
}
public boolean isPrime(int c)
{
boolean x = true;
for(int i = 3; i < (int)(Math.sqrt(c)) + 1; i++)
{
if(c % i == 0)
{
x = false;
}
if(c % 2 == 0)
{
x = false;
}
}
return x;
}
public void countPrimes(int upperLimit)
{
this.upperLimit = upperLimit;
int counter = 0;
System.out.println("The prime numbers between 1 and " + this.upperLimit + " are:");
for(int n = 1; n < this.upperLimit; n++)
{
if(isPrime(n))
{
System.out.println(n);
counter++;
}
}
System.out.println("The amount of prime numbers between 1 and " + this.upperLimit + " is: " + counter);
}
}
我使用1000测试了这个程序。它似乎列出了范围内的所有素数,但也列出了4、6和8,它们不是素数。我不确定是什么原因造成了这种情况。功能应该是这样的,我认为这样可以工作:
public boolean isPrime(int c)
{
boolean x = true;
int j;
for (j=2; j<c;j++)
{
if(c%j==0)
{
break;
}
}
if(c==j)
{
return true;
}
return false;
}
public boolean isPrime(int c)
{
布尔x=真;
int j;
对于(j=2;j为什么在isPrime
中有一个特殊的if(c%2==0)
位,而不是从i=2
开始?(想想当c
小于9时,循环当前执行的频率有多高…@PeterLawrey:修复,谢谢:)一旦你确定了这个数字不是素数,为什么还要继续检查更多的数字呢?如果我改变它,它会起作用的,谢谢。现在我不太清楚为什么我会这样,因为我回头看。首先,所以n
应该从2
开始。另一方面,4,6,8
会被打印出来,因为你开始用3检查素数
而不是2
。没有必要达到c
。sqrt(c)+1
就足够了。它叫@Albert是的,我同意Albert,但是为了这个小逻辑,我们为什么要涉及任何数学函数。我假设对于任何初学者来说,代码都应该简单易懂。
public boolean isPrime(int c)
{
boolean x = true;
int j;
for (j=2; j<c;j++)
{
if(c%j==0)
{
break;
}
}
if(c==j)
{
return true;
}
return false;
}