-3

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

Abra
  • 19,142
  • 7
  • 29
  • 41
Faraj
  • 1

4 Answers4

1

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?

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

Change your conditional in your loop

for (int f = 2; f <= maxF; f++) { // should be <= maxf
     if (n % f == 0) {
        prime = false;
     }
}
WJS
  • 36,363
  • 4
  • 24
  • 39
  • 1
    Can you please help Hussain on [this question](https://stackoverflow.com/questions/64144653/how-to-change-colors-of-a-circle-using-a-timer-in-a-java-gui)? I am not so good with Swing API and he has contacted me for help. – Arvind Kumar Avinash Sep 30 '20 at 21:03
0

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

Meowster
  • 447
  • 3
  • 14
0

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;
    }
}
mumun
  • 51
  • 1
  • 8