aspose file tools*
The moose likes Beginning Java and the fly likes Finding n th prime number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Finding n th prime number" Watch "Finding n th prime number" New topic
Author

Finding n th prime number

rajarshi roy
Greenhorn

Joined: Feb 14, 2010
Posts: 21
I am trying to write a code for a program that will find the n th prime number.As for example 7 is the 4th prime number,11 is the 5th.
The method will take argument as n,and it will find the nth prime number.But I am facing some difficulty with the code.The code doesnt terminate by itself and doesnt return the desired value.Someone please help me out.
Dennis Grimbergen
Ranch Hand

Joined: Nov 04, 2009
Posts: 142

To loop till Integer.MAX_VALUE takes a while I guess. Besides that, this looping is also in a while loop. That calculation would takes ages, and that's why it doesn't stop by itself.

SCJP, SCWCD, SCJD
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

You loop from 0 to Integer.MAX_VALUE without checking the count. You only re-check count after this loop. Merge both loops into one:
This will still loop over i, but this single loop will stop once count == n.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
rajarshi roy
Greenhorn

Joined: Feb 14, 2010
Posts: 21
Rob Prime wrote:You loop from 0 to Integer.MAX_VALUE without checking the count. You only re-check count after this loop. Merge both loops into one:
This will still loop over i, but this single loop will stop once count == n.

I modified the code to take into account what you said..
The code compiles,runs and gives the desired output.But I am still facing one odd problem.
I am using Eclipse IDE for coding.Whenever I am trying to run the code,a dialogue box appears that says "Error exists in required project(s).......Proceed with launch?"
What does this mean??
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Means there's an error in your current project (or a required one, or something) that doesn't affect the running of the code you're using, or that it does and you've been running the same version of the app without realizing it. Open up the "Problems" tab (view) and see what's there.
Karthik Shiraly
Ranch Hand

Joined: Apr 04, 2009
Posts: 513
    
    6
I've a comment to make about the ifPrime check: To check divisibility of x, it's not needed to test all numbers from {2 to x} as factors; it's enough to test from {2 to squareroot(x) inclusive}. Take any pair of factors of x, which yield x on multiplication - one of the pair will always be less than or equal to squareroot(x).

 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Finding n th prime number