File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Find primes less than 100

 
Hui Zhao
Ranch Hand
Posts: 116
  • 0
  • 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
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • 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).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic