File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Generating Prime Number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generating Prime Number" Watch "Generating Prime Number" New topic

Generating Prime Number

Leigh Castillo

Joined: Jul 02, 2013
Posts: 2
I Just want to ask what is wrong about
my codes in generating the prime nos.

any reply would be appreciated. thanks!
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Hi Leigh, welcome to the Ranch!

Why don't you start by telling us why you think there is something wrong with your code. Does it not compile? Throw an exception when you run it? Read our FAQ entry TellTheDetails to find out about things which would be useful to anybody wanting to help out with the learning process.
Martin Vajsar

Joined: Aug 22, 2010
Posts: 3733

Your tests (i%j==0 and i==j) are true for every i, since your inner loop runs till j is equal to i.

It's not a good test either. Prime number is a number which is divisible only by one and itself. You should be looking for numbers (n) that do not have any divisor between 2 and n-1. Try to rewrite your condition that way.

(However, this is still quite inefficient way to find primes. There are many possible optimizations. For example, no prime except 2 is even, so you might put in 2 in advance and then only test odd numbers starting at three. And there are others. If you're really interested, I'd suggest doing a small research on prime numbers first.)
Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 178

There are lots of errors. It's good if you can study more about prime numbers..

Leigh Castillo

Joined: Jul 02, 2013
Posts: 2
Thanks guys to the replies..

I already find out the code
I just need to put break when the no. didn't passed 2nd condition..

Thanks again ^^
I agree. Here's the link:
subject: Generating Prime Number
It's not a secret anymore!