Java Prime finder效率

时间:2016-03-05 10:08:32

标签: java performance square-root

我想总结所有值小于10的素数。

这是我的代码:

    boolean kontroll = true;
    long limit = 10;
    long checker = 2;
    long sum = 0;

    while (checker < 10) {
        for (long i = 3; i < Math.sqrt(checker); i += 2) {
            if (checker % 2 == 0) {
                kontroll = false;
                break;
            } else {
                if (checker % i == 0) {
                    kontroll = false;
                } 
            }
        } if (kontroll) {
            sum += checker; 
            System.out.println("Prim: " + checker);
        }
        checker++;
        kontroll = true;
    }
    System.out.println(sum);

我得到了这个输出:

Prim: 2
Prim: 3
Prim: 4
Prim: 5
Prim: 6
Prim: 7
Prim: 8
Prim: 9
44

这个版本有什么问题?如果我删除Math.sqrt(checker);程序有效,但速度很慢。我不能拿检查器的平方根吗?

3 个答案:

答案 0 :(得分:1)

3为非负数且<8>时,

Math.sqrt(checker)大于checker

试试这个:

boolean kontroll = true;
long limit = 10;
long checker = 2;
long sum = 0;

while (checker < 10) {
    if (checker != 2 && checker % 2 == 0) { // move this check out of the loop and correct condition
        kontroll = false;
    } else {
        long max = (long)Math.sqrt(checker);
        for (long i = 3; i <= max; i += 2) { // change < to <=
            if (checker % i == 0) {
                kontroll = false;
                break; // add break for better performance
            } 
        }
    }
    if (kontroll) {
        sum += checker; 
        System.out.println("Prim: " + checker);
    }
    checker++;
    kontroll = true;
}
System.out.println(sum);

答案 1 :(得分:0)

您的kontroll变量已分配true,您正在从3循环到sqrt(checker),您的情况checker将低于10 }}

因此,您的代码只会在checker = 103 < sqrt(10))时进入您的循环,其他时间,它们只会进入

if (kontroll) { //remember, your kontroll assigned to true =)
    sum += checker; 
    System.out.println("Prim: " + checker);
} 

并且总是会添加总和。干杯!

答案 2 :(得分:0)

一个优化版本,可打印最多为某个数字的素数。

final List<Integer> primes = new ArrayList<>(Collections.singletonList(2));

/**
 * Print prime numbers up to {@code n} inclusive
 */
public void findPrimes(int n) {
    // check only odd numbers
    for (int i = 3; i <= n; i += 2) {
        isPrime(i);
    }
    System.out.println(primes);
}

// a function which does have side effects (adds to the primes collection)
private boolean isPrime(final int i) {
    // we really need to check for divisors only up to sqrt
    int sqrt = (int)Math.sqrt(i);
    // and we really need to find only prime divisors since any
    // number can be written as a product of prime numbers
    for (int prime : primes) {
        if (i % prime == 0) {
            return false;
        }
        if (prime > sqrt) {
            break;
        }
    }
    primes.add(i);
    return true;
}