Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Find primes less than 100

 
Hui Zhao
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am almost there.
But I got an error which 99 is a prime.
And print many times.


Thanks for your help.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, why do you have the line:

Prime p = new Prime();

in your program?

Also, you are not using anything in class java.lang.Math, so you do not need to import it. In fact, you never have to import anything from the package java.lang - that package is always automatically imported.

About the problem: Notice that the break statement breaks out of the innermost loop. So, in your program it breaks out of the loop over j. What you probably want to do here, is continue with the next value of i (instead of just the next value of j).

To understand why the program reports that 99 is a prime (which is ofcourse false), follow in your head what happens if i = 99. What will j loop from and to? Under which circumstance does it reach the println statement?

(Note that your algorithm is OK, but it is not the most efficient way to find primes. See Sieve of Erathostenes).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic