猿问

根据在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 时会发生什么。谁能告诉我我的代码中的错误?


jeck猫
浏览 141回答 3
3回答

开心每一天1111

在这种情况下使用嵌套循环会使事情变得更加复杂。我建议您将解决方案分为两个步骤:创建一个函数来确定一个数是否为素数。private static boolean isPrime(int n) {&nbsp; &nbsp; //check if n is a multiple of 2&nbsp; &nbsp; if (n % 2 == 0) return false;&nbsp; &nbsp; //if not, then just check the odds&nbsp; &nbsp; for (int i = 3; i * i <= n; i += 2) {&nbsp; &nbsp; &nbsp; &nbsp; if (n % i == 0)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}用循环找出前 N 个素数:System.out.print("Enter Range: ");int range = input.nextInt();int count = 0;for (int number = 2; count < range; number++) {&nbsp; &nbsp; if (isPrime(number)) {&nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(number);&nbsp; &nbsp; }}

Smart猫小萌

另一种解决方案)public static boolean checkPrime(int i) {&nbsp; &nbsp; if (i <= 1)&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; else if (i <= 3)&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; else if (i % 2 == 0 || i % 3 == 0)&nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; int n = 5;&nbsp; &nbsp; while (n * n <= i) {&nbsp; &nbsp; &nbsp; if (i % n == 0 || i % (n + 2) == 0)&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; n = n + 6;&nbsp; &nbsp; }&nbsp; &nbsp; return true;&nbsp; }public static void main(String[] args) throws Exception {&nbsp; &nbsp; int isPrime = 0;&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; int size = 10;&nbsp; &nbsp; while (isPrime < size) {&nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; if (checkPrime(counter)) {&nbsp; &nbsp; &nbsp; &nbsp; isPrime++;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(counter);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答