gpt4 book ai didi

java - 显示一定数量的素数

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:21 25 4
gpt4 key购买 nike

我一直在编写一些 java 代码来显示素数。我已经让它显示 0 到 100 之间的所有素数。

我该如何设置才能将变量设置为 20,它会显示前 20 个素数。

我的代码:

public class PrimeNumber {

/**
* @param args the command line arguments
*/
private static boolean prime = true;
private static int count = 20;

public static void main(String[] args) {

for (int i = 2; i < 100; i++) {
for (int j = 2; j < 100; j++) {
if(i == j)
{
continue;
}
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
}

}

}

}

最佳答案

这是 OP 代码的最简单的实现。

减少count变量并在外部for循环中检查它,直到达到。此外,内部 for 循环应仅检查 (i/2 + 1) 的当前值。另一半你可以随时跳过,该值将除以数字本身。

public class PrimeNumber {    
/**
* @param args the command line arguments
*/
private static boolean prime = true;
private static int count = 20;

public static void main(String[] args) {

for (int i = 2; count>0; i++) {
for (int j = 2; j < i/2 + 1; j++) {
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
count--;
}
}
}
}

关于java - 显示一定数量的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33121292/

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