java 前 1000 个素数的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16994861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:38:32  来源:igfitidea点击:

Sum of first 1000 prime numbers

java

提问by lurker

I have the below program where I am trying to find the sum of first 1000 prime numbers. In the code, what's the difference between solution 1, and 2? Why should I not put the count variable outside the if condition? I am obviously not getting the answer I need if I put the variable outside if, but I don't understand why its logically wrong. It could be a simple thing, but I am unable to figure it out. Experts, please help.

我有下面的程序,我试图在其中找到前 1000 个素数的总和。在代码中,解决方案1和2有什么区别?为什么我不应该将 count 变量放在 if 条件之外?如果我把变量放在 if 之外,我显然没有得到我需要的答案,但我不明白为什么它在逻辑上是错误的。这可能是一件简单的事情,但我无法弄清楚。请高手帮忙。

Solution 1:

解决方案1:

public class SumOfPrimeNumbers {
public static void main(String[] args) {
    long result = 0;
    int number = 2;
    int count = 0;
    while (count < 1000) {
        if (checkPrime(number) == true) {
            result = result + number;
            count++;
        }
        number++;
    }
    System.out.println("The sum of first 1000 prime numbers is " + result);
}

public static boolean checkPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            return false;
        }
    }
    return true;
}

}

}

Solution 2:

解决方案2:

public class SumOfPrimeNumbers {    
public static void main(String[] args) {
    long result = 0;
    int number = 2;
    int count = 0;
    while (count < 1000) {
        if(checkPrime(number)==true)
        {
        result = result + number;                       
        }               
        count++; //The count variable here has been moved to outside the loop.
        number++;
    }       
    System.out.println("The sum of first 1000 prime numbers is "+ result);
}

public static boolean checkPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0) {
            return false;
        }
    }       
    return true;
}

}

}

回答by dasblinkenlight

You should not check the return value of boolfunctions for equality to true: this line

您不应该检查bool函数的返回值是否等于true:此行

if(checkPrime(number)==true)

is equivalent to

相当于

if(checkPrime(number))

Finally, the solution where the count is incremented outside of ifcounts non-primes together with primes, producing an obviously wrong result.

最后,计数在计数之外递增的解决方案if将非素数与素数一起计数,产生明显错误的结果。

Here are a couple of points "for style" that you should consider:

以下是您应该考虑的“风格”几点:

  • Checking candidate divisors in checkPrimecan stop when the candidate divisor is greater than the square root of the number
  • You can do much better if you store the primes that you've seen so far, and checking divisibility only by the numbers from the list of primes. When you are looking for the first 1000 primes this would hardly matter, but for larger numbers this could be significant.
  • checkPrime当候选因数大于该数的平方根时,可以停止检查候选因数
  • 如果您存储迄今为止看到的素数,并仅通过素数列表中的数字检查可整性,您可以做得更好。当您在寻找前 1000 个素数时,这无关紧要,但对于较大的数字,这可能很重要。

回答by Blender

The place where you increment countis pretty important. Your first code chunk adds up the first 1000 primes, while the second one adds up all the primes less than 1000.

你增加的地方count很重要。您的第一个代码块将前 1000 个质数相加,而第二个将所有小于 1000 的质数相加。

回答by lurker

In your solution 2, countis incremented EVERY time through the loop, regardless of the result of your prime test. So it is not counting primes, but counting iterations through the loop. As a result, you'll check 1,000 consecutive numbers, not consecutive primes (which involves going through a lot more than 1,000 numbers to accumulate).

在您的解决方案 2 中,count无论您的主要测试结果如何,每次循环都会增加。所以它不是计算素数,而是计算循环中的迭代次数。因此,您将检查 1,000 个连续的数字,而不是连续的质数(这涉及通过 1,000 个以上的数字来累积)。

In addition to what others have pointed out, your check for prime can be made a little more efficient by:

除了其他人指出的内容之外,您可以通过以下方式更有效地检查素数:

public static boolean checkPrime(int number) {
    int s = Math.ceil(Math.sqrt(number));

    for (int i = 2; i <= s; i++) {
        if ((number % i) == 0) {
            return false;
        }
    }       
    return true;
}