我想知道是否有更有效的方式来运行这个程序?
它适用于较低的数字,但随着时间的推移,时间也会增加 - 指数级.所以像1000000这样的数字永远都需要
import java.util.*;
public class SumOfPrimes {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
long number = 0;
System.out.println("This program outputs the sum of the primes of a given number.");
System.out.print("Please enter a number: ");
number = in.nextLong();
System.out.println("The sum of the primes below "+number+" is: "+sumOfPrimes(number));
}
public static long sumOfPrimes(long n){
long currentNum = 2;
long sum = 0;
if (n > 2){
sum = sum + 2;
}
while (currentNum <= n) {
if (currentNum % 2 != 0 && isPrime(currentNum)) {
sum = sum + currentNum;
}
currentNum++;
}
return sum;
}
public static boolean isPrime(long currentNum){
boolean primeNumber = true;
for (long test = 2; test < currentNum; test++) {
if ((currentNum % test) == 0){
primeNumber = false;
}
}
return primeNumber;
}
}
Run Code Online (Sandbox Code Playgroud)
有更好的寻找算法,但作为一个快速修复,你只需要通过当前数字的平方根测试因子,因为如果你找到一个高于平方根的因子,那么你应该找到一个低于平方根.
long stop = (long) Math.sqrt(currentNum);
for (long test = 2; test <= stop ; test++) {
Run Code Online (Sandbox Code Playgroud)
此外,false如果您找到了一个因子,那么就会突破循环并返回,从而证明数字复合.
如果需要更高的效率,您可以实施Eratosthenes筛选,以便您只检查本身可能的因素.
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |