A prime number is a number that has exactly two factors: 1 and itself. The first few prime numbers are:
\[ 2,3,5,7,11,13,17,19,… \]In this tutorial, we will write a Python program to find the Nth prime number, where N is a user-defined value.
Python Program to Find the Nth Prime Number
Method 1: Using a Loop and Prime Check
# Function to check if a number is prime def is_prime(num): if num < 2: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True # Function to find the Nth prime number def nth_prime(n): count = 0 # Count of prime numbers found num = 1 # Starting number to check while count < n: num += 1 if is_prime(num): count += 1 return num # Taking user input N = int(input("Enter the value of N: ")) # Finding and displaying the Nth prime number print(f"The {N}th prime number is: {nth_prime(N)}")
Output
Enter the value of N: 5 The 5th prime number is: 11
Method 2: Using a Prime Number List
If you need to find multiple prime numbers efficiently, you can store primes in a list instead of checking each number individually.
def nth_prime(n): primes = [2] # List of found primes num = 3 # Start checking from 3 while len(primes) < n: if all(num % p != 0 for p in primes if p * p <= num): primes.append(num) num += 2 # Skip even numbers return primes[-1] # Taking user input N = int(input("Enter the value of N: ")) # Finding and displaying the Nth prime number print(f"The {N}th prime number is: {nth_prime(N)}")
This method is faster because it avoids unnecessary calculations by checking divisibility with only stored primes.