This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 18541

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: 3606

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: 169

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
Similar Threads
Sieve of Eratosthenes
Java Code puzzle
Convert array to array of arrays
problem in prime numbers using an array
Find primes less than 100