根据Java中输入的范围显示所有素数

时间:2018-10-01 10:49:59

标签: java

我正在尝试解决一个示例练习,该练习将根据输入的范围显示素数。例如,如果我输入10,则应输出2 3 5 7 11 13 17 19 23 29

这是我的代码:

System.out.print("Enter Range: ");
int range = input.nextInt();

int r = 0;
for(int ctr1 = 2; ctr1 <= range; ctr1++){
    for(int ctr2 =  1; ctr2 <= ctr1; ctr2++){
        if(ctr1%ctr2 == 0){
          r++;      
        }
    }
    if(r == 2){
        System.out.println(ctr1);
    }
}

发生什么事,当我输入10时它只输出2。有人可以告诉我代码中的错误吗?

谢谢...

3 个答案:

答案 0 :(得分:2)

在这种情况下,使用嵌套循环可能会使事情变得更复杂。我建议您将解决方案分为两个步骤:

  1. 创建一个determine if a number is prime的函数。

    private static boolean isPrime(int n) {
        //check if n is a multiple of 2
        if (n % 2 == 0) return false;
        //if not, then just check the odds
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
    
  2. 使用循环找到前N个质数:

    System.out.print("Enter Range: ");
    int range = input.nextInt();
    
    int count = 0;
    
    for (int number = 2; count < range; number++) {
        if (isPrime(number)) {
            count++;
            System.out.println(number);
        }
    }
    

答案 1 :(得分:0)

我不了解您的代码。尝试给出合理的参数名称。无论如何,这就是您要查找的代码。

public static void main(String args[]) {

    //get input till which prime number to be printed
    System.out.println("Enter the amount of prime numbers to be printed: ");
    int limit = new Scanner(System.in).nextInt();
    int count=1;

    //printing primer numbers till the limit ( 1 to 100)
    System.out.println("Printing prime number from 1 to " + limit);
    for(int number = 2; count<=limit; number++){
        //print prime numbers only
        if(isPrime(number)){
            System.out.println(number);
            count++; 
        }
    }

}

/*
 * Prime number is not divisible by any number other than 1 and itself
 * @return true if number is prime
 */
public static boolean isPrime(int number){
    for(int i=2; i<number; i++){
        if(number%i == 0){
            return false; //number is divisible so its not prime
        }
    }
    return true; //number is prime now
}

答案 2 :(得分:0)

另一个解决方案)

public static boolean checkPrime(int i) {
    if (i <= 1)
      return false;
    else if (i <= 3)
      return true;
    else if (i % 2 == 0 || i % 3 == 0)
      return false;
    int n = 5;
    while (n * n <= i) {
      if (i % n == 0 || i % (n + 2) == 0)
        return false;
      n = n + 6;
    }
    return true;
  }



public static void main(String[] args) throws Exception {
    int isPrime = 0;
    int counter = 0;
    int size = 10;
    while (isPrime < size) {
      counter++;
      if (checkPrime(counter)) {
        isPrime++;
        System.out.println(counter);
      }
    }
  }