似乎您的隐式参数 int number 从未在您的程序中使用过。试试这个代码:
private static int countPrimes(int number){
int count =0;
int countPrimes=0;
if(number<2)
return 0;
for(int i=2; i<=number; i++) { //start i=2, because you know that 1 is not a prime number.
for(int j=1; j<=i; j++){
if(i%j==0)
count++;
}
if(count ==2)
countPrimes++;
count=0;
}
return number;
}
然后,在您的 runner 方法中,调用:
int numOfPrimes = countPrimes(10000);
在此,您可以更改要计数的数字。在这个例子中,它计算的素数最多为 10000。
int numOfPrimes = countPrimes(100);
这将计数最多 100 个素数。如果要跟踪素数,可以在程序中添加:
ArrayList<Integer> listOfPrimes = new ArrayList<Integer>();
private static int countPrimes(int number){
int count =0;
int countPrimes=0;
if(number<2)
return 0;
for(int i=2; i<=number; i++) { //start i=2, because you know that 1 is not a prime number.
for(int j=1; j<=i; j++){
if(i%j==0)
count++;
}
if(count ==2){
countPrimes++;
listOfPrimes.add(i);
}
count=0;
}
return number;
}
为了检索您的号码,您可以执行以下操作:
System.out.println("Exactly "+ countPrimes(number) + " prime numbers exist between "+ "1" + " and " + number + ".");
System.out.println("These numbers are: ");
for(int i =0; i<listOfPrimes.size();i++){
System.out.println(listOfPrimes.get(i));
}