From 90f7c463837bd909ce0b05c3d9e99757c8d2b96b Mon Sep 17 00:00:00 2001 From: IMACULGY Date: Sun, 13 Oct 2019 12:23:39 -0400 Subject: [PATCH] Added NthPrime.java --- Math/NthPrime.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Math/NthPrime.java diff --git a/Math/NthPrime.java b/Math/NthPrime.java new file mode 100644 index 00000000..3187cffb --- /dev/null +++ b/Math/NthPrime.java @@ -0,0 +1,39 @@ +public class NthPrime +{ + //------------------------------------- + // Finds the nth prime number for user-inputted value of n + //------------------------------------- + public static int FindNthPrime(int num) + { + int primeCount = 0, i = 1; + + //Check all numbers until n primes are found. + while (primeCount < num) + { + i++; + //Increment the number of primes found if the number is prime. + if (isPrime(i)) + primeCount++; + } + + //Return the nth prime number. + return i; + } + + //-------------------------------------- + // Helper method for FindNthPrime + // Returns true if the number is prime, false otherwise + //-------------------------------------- + private static boolean isPrime(int num) + { + //Check for integer divisors of num + for (int i = 2; i < num; i++) + { + //If num is divisible by any number between 1 and num, the number is not prime + if (num % i == 0) + return false; + } + //If no integer divisors are found, the number is prime. + return true; + } +} \ No newline at end of file