Skip to content

Instantly share code, notes, and snippets.

@ad2476
Created May 5, 2014 03:46
Show Gist options
  • Save ad2476/84a701fe2e661a87ec3a to your computer and use it in GitHub Desktop.
Save ad2476/84a701fe2e661a87ec3a to your computer and use it in GitHub Desktop.
Nth Prime
/* Returns the nth prime number - uses the Sieve of Eratosthenes */
public int calculatePrime(int limit, int n) {
List<Integer> working_set = new ArrayList<Integer>();
int p=2;
// Fill our working set with consecutive integers (longs) from 2 through n
System.out.println("Populating working set...");
for(int i=2; i<=limit; i++)
working_set.add(i);
System.out.println("Finding primes...");
// The working set will shrink until hopefully it contains only primes
for(int i=0; i<working_set.size(); i++) {
// Enumerate multiples of p and mark them (in our case, just remove them)
for(int j=p; j<working_set.size(); j++) {
int current=working_set.get(j);
if(current%p == 0) { // current is a multiple of p
working_set.remove(j); // "Mark" this number - i.e. remove from our working set
j--;
}
}
p=working_set.get(i);
System.out.println(p);
}
if(n<=working_set.size())
return working_set.get(n-1);
else
return -1*working_set.size(); // If there aren't that many primes, return the size of the working set
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment