|
| 1 | +package medium; |
| 2 | + |
| 3 | +/** |
| 4 | + * Have the function PrimeMover(num) return the numth prime number. |
| 5 | + * The range will be from 1 to 10^4. |
| 6 | + * --- |
| 7 | + * For example: if num is 16 the output should be 53 as 53 is the 16th prime number. |
| 8 | + */ |
| 9 | +public class PrimeMover { |
| 10 | + |
| 11 | + /** |
| 12 | + * Check if a given number is a prime number. |
| 13 | + * |
| 14 | + * @param num input number |
| 15 | + * @return true if is a prime number |
| 16 | + */ |
| 17 | + private static boolean isPrimeNumber(int num) { |
| 18 | + // prime numbers are greater than 1 |
| 19 | + if (num <= 1) { |
| 20 | + return false; |
| 21 | + } |
| 22 | + // 2 is an only even prime number |
| 23 | + // http://mathworld.wolfram.com/EvenPrime.html |
| 24 | + if (num == 2) { |
| 25 | + return true; |
| 26 | + } |
| 27 | + // eliminate all even numbers to reduce time complexity |
| 28 | + // (cannot be a prime number if is divisible by 2) |
| 29 | + if (num % 2 == 0) { |
| 30 | + return false; |
| 31 | + } |
| 32 | + // no need to check the entire range from 0 to num |
| 33 | + // (square root of num) + 1 is the sufficient upper limit |
| 34 | + // which greatly reduces time complexity |
| 35 | + double upper = Math.sqrt(num) + 1; |
| 36 | + // since the even numbers are eliminated, we can check the odd numbers only |
| 37 | + for (int i = 3; i < upper; i += 2) { |
| 38 | + if (num % i == 0) { |
| 39 | + // not a prime number |
| 40 | + return false; |
| 41 | + } |
| 42 | + } |
| 43 | + // must be a prime number! |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Prime Mover function. |
| 49 | + * |
| 50 | + * @param num input number |
| 51 | + * @return Nth prime number where N = num |
| 52 | + */ |
| 53 | + private static int primeMover(int num) { |
| 54 | + int i = 1; |
| 55 | + int primes = 0; |
| 56 | + while (primes < num) { |
| 57 | + if (isPrimeNumber(i)) { |
| 58 | + primes++; |
| 59 | + } |
| 60 | + i++; |
| 61 | + } |
| 62 | + return i - 1; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Entry point. |
| 67 | + * |
| 68 | + * @param args command line arguments |
| 69 | + */ |
| 70 | + public static void main(String[] args) { |
| 71 | + int result1 = primeMover(9); |
| 72 | + System.out.println(result1); |
| 73 | + int result2 = primeMover(100); |
| 74 | + System.out.println(result2); |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments