TenThousandAndFirstPrime.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /* By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
  2. that the 6th prime is 13.
  3. What is the 10,001st prime number?
  4. */
  5. import java.util.ArrayList;
  6. public class TenThousandAndFirstPrime {
  7. // To see if a given number is prime or not
  8. private static boolean checkPrime(long num) {
  9. /* If a number can be evenly divided by a number other than one and itself,
  10. it's prime, and a number cannot be evenly divided by a number greater
  11. than it */
  12. for (long i = 1; i < num; i++) {
  13. if (num % i == 0 && i != 1)
  14. return false;
  15. }
  16. return true;
  17. }
  18. public static long get10001stPrime() {
  19. // To know which prime number is in the 10001st spot
  20. ArrayList<Long> primes = new ArrayList<Long>();
  21. // To check if each number is a prime, in order
  22. long i = 1;
  23. /* To add all the prime numbers to the array, and stop after the desired
  24. index is reached */
  25. while (primes.size() < 10002) {
  26. // To see if a number is prime or not
  27. if ( checkPrime(i) )
  28. primes.add(i);
  29. i++;
  30. }
  31. // 10001st prime's index will be 10001
  32. return primes.get(10001);
  33. }
  34. }