gpt4 book ai didi

java - While 循环 1 - 100 之间的素数

转载 作者:行者123 更新时间:2023-11-30 02:12:24 24 4
gpt4 key购买 nike

我对编程还很陌生,我正在努力理解循环。我设法让一段代码正常工作,但我仍然没有完全理解它是如何工作的。我在网上找到了一个类似程序的代码,该程序是使用 for 循环编写的,并且我设法让它作为 while 循环工作(花了我几天的时间!!!)。我试图了解内部循环在做什么。

我知道外循环正在检查循环的每次迭代的x是否小于100。为什么需要在循环中嵌套y变量,为什么将其设置为2以及为什么每次都需要加1?另外,有没有办法在不使用 break; 的情况下退出循环?

我在这里看到了此类程序的一些其他示例,但我希望有人能够阐明这个程序的具体工作原理。

提前致谢!!!

class PrimeNumbers {
public static void main(String args[]) {
int x = 2;
while (x <= 100) {
int y = 2;
while (y <= x) {
if (x == y) {
System.out.println(x);
}
if (x % y == 0) {
break;
}
y++;
}
x++;
}
}
}

最佳答案

评论是你的 friend :

class PrimeNumbers {
public static void main(String args[]) {
// No point checking below 2 since the definition of a prime is "A prime number (or a prime) is a natural number greater than 1 ..."
int x = 2;
// Looking for primes up-to and including 100
while (x <= 100) {
// Same argument as above - start checking at 2 and work upwards.
int y = 2;
// stop when y > x as obviously y will not divide x
while (y <= x) {
// if y reaches x then we have not found any divisors
if (x == y) {
// success! This x is prime.
System.out.println(x);
}
// if y divides x leaving no remainder then not prime - give up this y loop and select our next x
if (x % y == 0) {
break;
}
// Try next y divisor.
y++;
}
// Try next x candidate.
x++;
}
}
}

并为变量命名更有帮助,它会变得更加容易

class PrimeNumbers {
public static void main(String args[]) {
// No point checking below 2 since the definition of a prime is "A prime number (or a prime) is a natural number greater than 1 ..."
int candidate = 2;
// Looking for primes up-to and including 100
while (candidate <= 100) {
// Same argument as above - start checking at 2 and work upwards.
int divisor = 2;
// stop when divisor > candidate as obviously divisor will not divide candidate
while (divisor <= candidate) {
// if divisor reaches candidate then we have not found any divisors (because of the `break` below).
if (candidate == divisor) {
// success! This candidate is prime.
System.out.println(candidate);
}
// if divisor divides candidate leaving no remainder then not prime - give up this divisor loop and select our next candidate
if (candidate % divisor == 0) {
break;
}
// Try next divisor.
divisor++;
}
// Try next candidate.
candidate++;
}
}
}

关于java - While 循环 1 - 100 之间的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49673888/

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