GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Find primes less than 100 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Find primes less than 100" Watch "Find primes less than 100" New topic
Author

Find primes less than 100

Hui Zhao
Ranch Hand

Joined: Jul 09, 2007
Posts: 116
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

Joined: Aug 16, 2005
Posts: 14192
    
  20

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).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
GeeCON Prague 2014
 
subject: Find primes less than 100