gpt4 book ai didi

Java Prime 查找器效率

转载 作者:行者123 更新时间:2023-12-01 10:17:22 24 4
gpt4 key购买 nike

我想对所有小于 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); 程序可以工作,但速度很慢。我不能取检查器的平方根吗?

最佳答案

checker 为非负数且小于等于 8 时,

3 大于 Math.sqrt(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);

关于Java Prime 查找器效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com