In this, we’ll write a program that will test if the given number which is greater than 1 is prime or not.
A prime number is a positive integer greater than 1 and which has only two factors 1 & the number itself for example number: 2, 3, 5, 7… etc are prime numbers as they have only two factors .i.e. 1 & the number itself.
# Python program to check if the input number is prime or not #Take input from the user num = int(input("Please enter the number: ")) #Check if the given number is greater than 1 if num > 1: # Iterate through 2 to num/2. for i in range(2,num//2): #Select if the number is divisible by any number between 2 and num/2. if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: #If given number is not fully divisible by any number between 1 and num/2, then its prime. print(num,"is a prime number") # Also, if the number is less than 1, its also not a prime number. else: print(num,"is not a prime number")
Output
Please enter the number: 47 47 is a prime number >>> ================= RESTART: C:/Python/Python361/primeNum1.py ================= Please enter the number: -2 -2 is not a prime number >>> ================= RESTART: C:/Python/Python361/primeNum1.py ================= Please enter the number: 3333 3333 is not a prime number 3 times 1111 is 3333
User-Input 1: num: 47
Output: Number(47) is a prime number
User-Input 2: num = -2
Output: Number(-2) is not a prime number
User-Input 3: num = 3333
Output: Number(3333) is not a prime number
In the above program, we check if the user input number is prime or not. Because numbers less than or equal to 1 are not prime numbers, therefore we only consider user-input greater than 1.
Then we check if the user-input is exactly divisible by any number between 2 to user-input/2. If we find a factor in that range, the number is not a prime number else, it’s a prime number.