Last active
January 1, 2020 21:15
-
-
Save realslimshanky/9251db1c5a53cd8c1c5b772351f0cfb5 to your computer and use it in GitHub Desktop.
Finding nth prime number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| 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