我正在尝试从用户找到给定数字之前的质数

问题描述 投票:0回答:1

我的代码无效,我也不知道为什么或如何使其正常工作。这是我的代码。

public static void ex5(){
    Scanner scan = new Scanner(System.in);
    int givenNr = scan.nextInt();
    int m = 1;
        for (int i = 2; i < givenNr; i++){
             while (m <= i/2 ){
                 if(i % m != 0) {
                     System.out.print(i + " ");
                 }
                 m++;
             }
            }
            }
java
1个回答
0
投票
public static void ex5() {
    Scanner scan = new Scanner(System.in);
    int givenNr = scan.nextInt();
    for (int i = 2; i < givenNr; i++) {
        if (isPrime(i))
            System.out.println(i);
    }
}

public static boolean isPrime(int n) {
    for (int i = 2; i <= Math.sqrt(n); i++) {
        if (n % i == 0)
            return false;
    }
    return true;
}
© www.soinside.com 2019 - 2024. All rights reserved.