我是一个业余的java学生,我的老师给了我这个作业,就是写一个列出前100个质数的代码。这是我到目前为止尝试过的。
for(int i =1; true; i++) {
int k = 0;
for(int j = 1; j <= i; j++) {
if(i % j == 0){
k ++;
}
if(k == 2) {
System.out.println(i);
}
}
}我遇到的问题是,即使我使用我熟悉的可能的机制,我也不能不停止控制台以在数到100后停止。例如:
for( int i =1; true; i++) {
int k = 0;
for(int j = 1; j <= i; j++) {
if(i % j == 0) {
k ++;
}
int m = 0;
if(k == 2) {
System.out.println(i);
m++;
if(m==100) {
break;
}
}
}
}在计算了100个素数后,我能得到帮助来终止循环吗?
发布于 2019-05-28 23:42:07
你需要跟踪你打印了多少质数,一旦达到100就停止打印。我已经在代码中使用注释解释了下面的代码。
public class Main
{
public static void main(String[] args) {
int k = 0; // to keep track of how many primes you have prited
int i = 2; // number to check for prime, increases every loop
while (k < 100){ // while you have printed less than 100 primes
boolean isPrime = true; // next few lines are checking i for prime and store it in this variable
for(int divisor = 2; divisor <= i / 2; divisor++) { // you should go with divisor <= Math.sqrt(i) in condition, I couldn't be bothered in import stuff.
if (i % divisor == 0) {
isPrime = false;
break; // i is not a prime, no reason to continue checking
}
}
if (isPrime){
System.out.println(i); // if i is prime, print it
k ++; // increase k by when a print number is found
}
i ++; // increase i to check next number
}
}
}发布于 2019-05-29 00:04:49
您的代码会运行到无限大,因为您将break放在了错误的位置。您的break退出内部循环,即for(int j = 1; j <= i; j++),尽管您应该以外部循环for( int i =1; true; i++)为目标,因为这是决定将打印多少数字的原因,内部循环只是检查数字是否为质数。
我已经在这段代码中更正了你的方法(注释中有解释)
int numbersPrinted = 0; // To keep track of how many numbers have been printed
for (int i = 2; true; i++) {
boolean isPrime = true; // Assuming the number is prime
for (int j = 2; j < i; j++) {
// Checking if any number from 2 to i-1 completely divides i
if (i % j == 0) {
// If a number completely divides (gives 0 remainder)
// The number is not prime
isPrime = false;
// You can use break here. I don't think it matters anyways.
}
}
if (isPrime) {
// Printing i only if it is prime
System.out.print(i + ", ");
numbersPrinted++; // Updating the numbersPrinted
}
// Checking if the numbers printed is grater than or equal to 100
if (numbersPrinted >= 100)
// This will break the outermost loop
// This is where you messed up
break;
}输出(恰好100个质数)
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 发布于 2019-05-28 23:55:52
要回答你的问题如何在100停止:
for( int i =1; i<=100; i++){for语句的第二个参数是继续的条件。如果此条件的计算结果为false,则for循环将停止迭代。
https://stackoverflow.com/questions/56345107
复制相似问题