java - 更有效的方法?

标签 java sum factors

我想知道是否有更有效的方法来运行这个程序?

对于较低的数字,它运行良好,但随着数字的增加,时间也会呈指数增长。所以像 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;
}
}

最佳答案

有更好的素数查找算法,但作为一个快速解决方案,您只需要测试当前数字的平方根以上的因子,因为如果您找到高于平方根的因子,那么您应该找到了低于平方根的因子。

long stop = (long) Math.sqrt(currentNum);
for (long test = 2; test <= stop ; test++) {

此外,如果您找到了一个因子并证明了数字的合数,则跳出循环并返回false

如果需要更高的效率,您可以实现 Sieve of Eratosthenes这样您就只检查可能的素数因子。

关于java - 更有效的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15489023/

相关文章:

R:在不创建新变量的情况下测试因子的每个水平

c++ - C/C++ 中大数的所有因数

r - 按因子水平划分的子设置观测值超过 x 个观测值

java - OpenJDK 11 错误 "Can not initialize cryptographic mechanism"

MySQL SUM 同时保持求和数据独立

java - 如何在 Java 的 TreeMap 中检索具有最大值的键?

mysql - 根据 PostgreSql 中单个查询中的日期求和

mysql - SQL 语法错误多次计数

java - 使用枚举会降低应用程序的可移植性吗?

java - Hibernate 查询 v 数据库函数