我有一个简单的目标代码。我还在学习Java,我的代码所做的是计算一定数量的素数总数(例如:从11到19有4个素数11,13,17,19)。到目前为止,我能够做的是显示素数(11,13,17,19),但我还想显示“4”作为11-19范围内的素数量。这是我的代码。
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the number till which prime number to be printed: ");
int limit = 19;
System.out.println("Printing prime number from 11 to " + limit);
for(int number = 11; number<=limit; number++){
if(isPrime(number))
{
System.out.println(number );
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
答案 0 :(得分:1)
int count = 0;
for(int number = 11; number<=limit; number++){
if(isPrime(number))
{
System.out.println(number);
count++;
}
}
System.out.println("Number of primes are :"+count);