Write a Python function to find the nth prime number.
Posted by DavidLee
Last Updated: August 07, 2024
Finding the nth prime number can be accomplished using a function that implements the Sieve of Eratosthenes algorithm or a straightforward approach to check for primality. Below is a Python function that utilizes a basic method for generating prime numbers until it reaches the nth prime.
Python Function to Find the nth Prime Number
def is_prime(num):
    """Helper function to check if a number is prime."""
    if num < 2:
        return False
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            return False
    return True

def nth_prime(n):
    """Function to find the nth prime number."""
    if n < 1:
        raise ValueError("n must be a positive integer.")
    
    count = 0  # To count the number of primes found
    candidate = 1  # Start checking for prime from 1
    
    while count < n:
        candidate += 1  # Move to the next number
        if is_prime(candidate):
            count += 1  # Found a prime number
            
    return candidate

# Example usage:
nth = 10
print(f"The {nth}th prime number is: {nth_prime(nth)}")
Explanation:
1. is_prime Function: This helper function checks if a given number is prime. It returns False for numbers less than 2 and checks for factors up to the square root of the number for efficiency. 2. nth_prime Function: This function finds the nth prime: - It initializes a counter (count) to track the number of prime numbers found and a candidate variable starting from 1. - A while loop continues until the desired n primes are found. - For each candidate number, it checks if it is prime using the is_prime function. If it is, the counter increments. - When the counter reaches n, the function returns the latest prime number found.
Example Usage:
Using this function, you can find any nth prime by calling nth_prime(n), where n is a positive integer indicating which prime number to find. For instance, calling nth_prime(10) will return the 10th prime number. This implementation is efficient for small values of n, but improvements can be made for larger values by considering more advanced algorithms like the Sieve of Eratosthenes for generating a list of prime numbers.