Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Finding the nth prime?

843789Apr 4 2010 — edited Apr 9 2010
Hi All,

I am newish to java and have written the following to find the nth prime number. I think it is probably overcomplicated, but it takes ages to execute and it is not that complicated. I would appreciate it is anyone could explain why this takes so long to execute; I assume it is a flaw with the code. If anyone could demonstrate a more efficient way to do this I would be interested.

class findnthprime{
	public static void main(String[] args){
	int[] primearray = {2};
	int nthprime = 6;
	int count = 1;
for(int i=2;count<=nthprime;i++){
for(int j = 0;j<primearray.length;j++){
	if((i%primearray[j])==0){
		if(i==j){
		primearray[count - 1]=j;
		primearray = new int[count + 1];
		count++;
			}
		}
	}
	}
System.out.println("Prime " + nthprime + " is " +  primearray[numberofprimes -1]);

	}
}
This compiles btw it just effectively never finishes executing.


Thanks
soundofsilence
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 7 2010
Added on Apr 4 2010
18 comments
676 views