我是java的初学者,无法理解" count"在这个程序中。我必须在用户输入的某个范围之间打印素数。
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int start, end, i, j, count=0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Range :\n");
System.out.print("Enter Starting Number : ");
start = scan.nextInt();
System.out.print("Enter Ending Number : ");
end = scan.nextInt();
System.out.print("Prime Numbers Between " + start + " and " +end+ " is :\n");
for(i=start; i<=end; i++)
{
count = 0;
for(j=2; j<i; j++)
{
if(i%j == 0)
{
count++;
break;
}
}
if(count == 0)
{
System.out.print(i + " ");
}
}
}
}
答案 0 :(得分:1)
count
作为指标。当它是0
时,数字是素数。它可以替换为boolean
:
boolean prime = true;
...
for(i=start; i<=end; i++) {
prime = true;
for(j=2; j<i; j++) {
if(i%j == 0) {
prime = false;
break;
}
}
if (prime) {
System.out.print(i + " ");
}
}
答案 1 :(得分:0)
计数用作参考来跟踪一个数字被划分的次数,如果除数数为0则算法知道该数字是素数