Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 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 Reply

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...