简体   繁体   中英

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

My code doesn't work and i don't know either why or how to make it work. This is my code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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