This simple Python program checks whether a given positive integer is a prime number using trial division
The program consists of three main functions:
-
get_input(): Prompts the user to enter a positive integer. It ensures the input is valid and positive through a loop that continues until the input meets the conditions. -
is_prime(n): Determines if the given numbernis a prime. The function handles base cases (e.g., n <= 1 and n == 2), checks even numbers, and dividesnby every odd number up to the square root ofn. -
main(): Controls the flow of the program, callingget_input()to retrieve the user's number andis_prime()to check its primality. The result is then printed.
- Ensure you have Python installed on your computer
- Save the script in a file, for example
prime_checker.py - Open a terminal or command prompt
- Navigate to the directory where the script is saved
- Run the script using the command:
python trial_division.py- Follow the on-screen prompts to input a positive integer
The script will then output whether the entered number is prime or not.
- Input validation to only accept positive integers
- Efficient primality testing using trial division up to the square root of the input number
Feel free to modify and use this code as part of your own projects!