繁体   English   中英

我正在尝试从用户那里找到从 0 到给定数字的素数

[英]I am trying to find the prime numbers from 0 to a given number from the user

我的代码不起作用,我也不知道为什么或如何使它起作用。 这是我的代码。

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++;
             }
            }
            }
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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM