Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Finding nth prime number
'''
Description: Module to check the value of nth prime number
Author: Shashank Kumar | https://shanky.dev
'''
from math import sqrt
def is_prime(number):
'''
Primality check function
'''
if number % 2 == 0:
return number == 2
if number % 3 == 0:
return number == 3
n_sqrt = int(sqrt(number))
j = 5
step = 5
while j <= n_sqrt:
if number % j == 0:
return False
step = 6 - step
j += step
return True
def find_nth_prime(nth_position):
'''
Return nth prime
'''
number_to_check = 1
current_position = 0
while(True):
number_to_check += 1
if is_prime(number_to_check):
current_position += 1
if current_position == nth_position:
return number_to_check
if __name__ == '__main__':
'''
Integrating everything together to make it work
'''
try:
desired_position = input('Enter a natural number n to find nth prime number: ')
desired_position = int(desired_position)
if desired_position < 1:
raise ValueError
nth_prime = find_nth_prime(desired_position)
print(f'{desired_position}th prime is {nth_prime}')
except ValueError:
print(f'{desired_position} is not a natural number')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment