107k views
0 votes
I am writing a code that requires me to identify a positive integer as a prime (or not). I have looked at references on how to find it but it does not work for what I am trying to do. Below is the set of instructions. I have written the first half of the code and verified that it works. I am stuck on how to write the logic that identifies the prime based on the instructions.

-----
Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number.
Your program should use a loop to validate the positive integer and accept the input only when the user inputs a positive number.
Your code should be an efficient algorithm using the following note.
(Note: An even number is prime if it is 2. An odd integer is prime if it is not divisible by any odd integer less than or equal to the square root of the number.)
For the square root, import the math library (import math) and use math.sqrt() function)

User Himadri
by
4.6k points

1 Answer

3 votes

import math

number = int(input("Enter a number: "))

while number < 0:

number = int(input("Enter a number: "))

if number % 2 == 0:

if number == 2:

print("Your number is a prime.")

exit()

print("Your number is not a prime.")

exit()

elif number % 2 == 1:

i = 2

while i <= math.sqrt(number):

if number % i == 0:

print("Your number is not a prime ")

exit()

i += 1

print("Your number is a prime.")

I hope this helps!

User Kunal Kukreja
by
5.3k points