Results 1 to 3 of 3
Thread: Finding nth prime number
 04122010, 10:47 PM #1Member
 Join Date
 Apr 2010
 Posts
 1
 Rep Power
 0
Finding nth prime number
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.
Java Code:public class Problem{ /** * @param args */ public int findAns(int n){ int count=0; int ret=0; while(count<n){ for(int i=0;i<Integer.MAX_VALUE;i++){ if(ifPrime(i)){ count++; } ret=i; } } return ret; } public boolean ifPrime(int num){ boolean b=false; int i; for (i=2; i < num ;i++ ){ int n = num%i; if (n==0){ b=false; break; } } if(i == num){ b=true; } return b; } public static void main(String[] args) { // TODO Autogenerated method stub System.out.println(new Problem().findAns(10)); } }

Are you sure that you want both a for loop and a while loop here:
Java Code:while(count<n){ for(int i=0;i<Integer.MAX_VALUE;i++){ if(ifPrime(i)){ count++; } ret=i; } }
 04122010, 11:42 PM #3Senior Member
 Join Date
 Mar 2010
 Posts
 266
 Rep Power
 11
Similar Threads

Finding Largest Prime Factor
By perito in forum New To JavaReplies: 7Last Post: 11082010, 08:25 PM 
How to Determine prime number and making shape using loop?
By cyzash in forum New To JavaReplies: 10Last Post: 02202010, 08:25 PM 
Finding a number in array close to another number
By SteroidalPsycho in forum New To JavaReplies: 2Last Post: 02152010, 12:37 AM 
Prime Number  System print all the prime numbers ...
By pinkdreammsss in forum New To JavaReplies: 20Last Post: 04262009, 01:50 AM 
Finding the highest number
By jigglywiggly in forum New To JavaReplies: 7Last Post: 11042008, 08:14 AM
Bookmarks