A prime number or a composite
A number is entered. The program determines whether it is prime or compound.
Note. Prime are natural numbers greater than 1, which are divided only by 1 and themselves.
import math n = int(input()) if n < 2: print("A number must be 2 and more") quit() elif n == 2: print("It's prime number") quit() i = 2 limit = int(math.sqrt(n)) while i <= limit: if n % i == 0: print("This is composite number") quit() i += 1 print("It's prime number")
With comments:
# The math module contains the square root # extraction function - sqrt() import math # A number is entered and converted to the integer n = int(input()) # If the number is less than 2, # then it is neither complex nor prime if n < 2: print("A number must be 2 and more") # exit from the program quit() # If the number is 2, then it is prime. elif n == 2: print("It's prime number") # exit from the program quit() # variable-divisor, which will be # incremented by 1 in a cycle i = 2 # Limit of increase i. # (To check the simplicity of the number, it suffices to go over # the dividers from 2 to the square root of the given number.) limit = int(math.sqrt(n)) # While i does not exceed the limit, while i <= limit: # to check if n is divisible by the current divisor. # If it is been dividing, if n % i == 0: # then this is a composite number. Print the appropriate message print("This is composite number") # and exit from the program quit() # Increase the divisor by 1 i += 1 # Up to this point the program will reach, if in the cycle # it was not determined that the number is composite. # Since it is not a composite, it means a prime one. print("It's prime number")
Example of execution:
5003 It's prime number