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