I'm trying to print out prime number but not sure what's wrong with my code

69 views Asked by At

My code

void printPrimes (int max) {
    boolean prime;
    for (int n = 2; n < max; n++){
        prime = true;
        double maxF;
        maxF = Math.sqrt(n);
        for (int f = 2; f < maxF; f++) {
            if (n % f == 0) {
                prime = false;
            }
        }
        if (prime == true) {
            System.out.println(n + " is prime");
        }
    }
}

This the result I get

4 is prime
5 is prime
6 is prime
7 is prime
8 is prime
9 is prime
10 is prime
11 is prime

what do I do to fix this issue

4

There are 4 answers

0
mumun On

Because loop maximum should be less or equals to

Math.sqrt(number)

public class Main {
    public static void main(String[] args) {
        printPrimes(20);
    }
    
    
    static void printPrimes (int max) {
        for(int i=2;i<=max;i++){
            if(isPrime(i)){
                System.out.println(i+" is prime");    
            }
        }
    }
    
    static boolean isPrime(int number) {
        if(number < 2){
            return false;
        }
        for(int i=2;i<=Math.sqrt(number);i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }
}
1
WJS On

Change your conditional in your loop

for (int f = 2; f <= maxF; f++) { // should be <= maxf
     if (n % f == 0) {
        prime = false;
     }
}
0
rzwitserloot On

Debug your code. As in, take out a pen, be the computer. You answer, without running this code, what it should do. Then check what it actually does with a debugger (or sysout statements if you must). There where you find a difference, you found a bug.

For example, Math.sqrt(4), what's that? is 2 less than 2?

0
Meowster On

at least replace f < maxF with f*f <= max