Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...