此代码计算素数,但它是如何工作的? 我需要清楚地解释最后的if(波段)是做什么的。
public class Primes {
public static void main(String[] args) {
int m;
boolean band;
for (int i = 2; i < 100; i++) {
m = 2;
band = true;
while (band && m <i) {
if (i % m == 0) {
band = false;
} else {
m++;
}
}
if (band) {
System.out.println("The number " + i + " is prime");
}
}
}
}
答案 0 :(得分:3)
这只是在2 -99之间打印素数。
从for循环中,它迭代2到99之间的数字。在for循环中,它检查特定数字(i)是否可被m整除而没有任何剩余。如果剩余的增加m的值为1,直到m <1。我并重复这个过程。如果没有剩余则为素数,则将band设为true并打印输出。由于band现在是真的,它将退出while循环并转到for循环的下一次迭代。
答案 1 :(得分:2)
尝试将变量band
重命名为i_is_prime
,然后尝试跟踪逻辑。关键是这一个:
if (i%m==0) {
如果true
均分为m
,则该行会返回i
,这意味着i
不是素数。
答案 2 :(得分:1)
此方法是查找小于100的所有素数
// This is the dividend
int m;
// Whether can't divisible
boolean band;
// From 100 all digital lookup
for (int i=2;i<100;i++){
// Divisor increasing from 2
m=2;
// If not divisible, here defined as cannot be divided exactly by first, if we can find a divisor aliquot, the current number is not a prime
band=true;
// From 2 to the current number one by one
while(band && m <i){
// Remainder of 0, explain aliquot, band = false, jump out the while
if(i%m==0){
band=false;
}else{
// Remainder is not 0, i cannot be divided exactly by m, continue to verify the m + 1
m++;
}
}
// From 2 to i-1 cannot be divisible, that i was a prime number
if(band){
System.out.println("The number "+i+" is prime");
}
}
答案 3 :(得分:0)