gpt4 book ai didi

java - 如何在表格中输出素数

转载 作者:行者123 更新时间:2023-11-30 05:43:13 26 4
gpt4 key购买 nike

我正在开发一个项目,该项目接收一个起始数字和多个素数,然后输出一个表格,其中包含起始数字之后的每个素数,直到达到您的素数数量。我编写了一个程序来查找素数,但我无法将输出格式化为表格。我知道我需要使用嵌套的 for 循环来构建表,但我不知道如何开始它。这是到目前为止我的代码:

class Tester2{

public static void main(String[] args){
int number = 750000; //starting number
int nofn = 12; //number of primes to find
int primecount = 0;

while(primecount < nofn){
if(isPrime(number)){
primecount ++;
System.out.println(primecount + " " +number);
}
number++;
}
}


//determins if num is prime
private static boolean isPrime(int num){
int divisor = 2;
boolean itIsPrime;
while(num % divisor != 0){
divisor++;
}
if(divisor == num)
itIsPrime = true;
else
itIsPrime = false;
return itIsPrime;
}
}

目前我的代码返回

1 750019
2 750037
3 750059
4 750077
5 750083
6 750097
7 750119
8 750121
9 750131
10 750133
11 750137
12 750151

我正在寻找它返回

Row #: 1--> 750019 750037 750059 750077 750083 750097 750119 750121 750131 750133
Row #: 2--> 750137 750151

最佳答案

给你。我还改进了您的 isPrime 方法,使其循环直到 sqrt(num) 而不是 num,因此现在应该快得多:

public class Test {
public static void main(String[] args) {
int number = 750000; // starting number
int nofn = 100; // number of primes to find
int primecount = 0;
int row = 0, col = 0;

while (primecount < nofn) {
if (isPrime(number)) {
primecount++;
if (col++ == 0)
System.out.print(String.format("%3d-->", ++row));
System.out.print(String.format(" %6d", number));
if (col == 10) {
System.out.println();
col = 0;
}
}
number++;
}
}

private static boolean isPrime(int num) {
final int last = (int) Math.sqrt(num);
for (int divisor = 2; divisor <= last; ++divisor) {
if (num % divisor == 0)
return false;
}
return true;
}

}

输出:

  1--> 750019 750037 750059 750077 750083 750097 750119 750121 750131 750133
2--> 750137 750151 750157 750161 750163 750173 750179 750203 750209 750223
3--> 750229 750287 750311 750313 750353 750383 750401 750413 750419 750437
4--> 750457 750473 750487 750509 750517 750521 750553 750571 750599 750613
5--> 750641 750653 750661 750667 750679 750691 750707 750713 750719 750721
6--> 750749 750769 750787 750791 750797 750803 750809 750817 750829 750853
7--> 750857 750863 750917 750929 750943 750961 750977 750983 751001 751007
8--> 751021 751027 751057 751061 751087 751103 751123 751133 751139 751141
9--> 751147 751151 751181 751183 751189 751193 751199 751207 751217 751237
10--> 751259 751273 751277 751291 751297 751301 751307 751319 751321 751327

关于java - 如何在表格中输出素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301951/

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