Posted By

binaryadder on 10/15/11


Tagged


Versions (?)

Problem 7


 / Published in: Java
 

Project Euler Question 7:

"By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?"

Input: 10001

Output: 104743

  1. import java.math.*;
  2.  
  3. public class Prob7{
  4. public static void main(String[] argsv){
  5. int primenum = 0;
  6. long prime = 1; // I know 1 isn't a prime, but this makes the code easier to write
  7. int nth = new Integer(argsv[0]).intValue();
  8. while(primenum < nth){
  9. prime = nextPrime(prime);
  10. primenum++;
  11. }
  12. System.out.println(prime);
  13. }
  14.  
  15.  
  16. private static long nextPrime(long n){
  17. n++;
  18. while(!isPrime(n)){
  19. n++;
  20. }
  21. return n;
  22. }
  23.  
  24. private static boolean isPrime(long n){
  25. long limit = (long) Math.sqrt(n);
  26. for(long i = 2; i <= limit; i++){
  27. if(n % i == 0){
  28. return false;
  29. }
  30. }
  31. return true;
  32. }
  33. }

Report this snippet  

You need to login to post a comment.