我想知道是否有更有效的方法来运行这个程序?
它对于较低的数字运行良好,但随着您的增加,时间也会增加 - 呈指数增长。所以像 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;
}
}