In this post I am making a simple prime checker. The user will input a number and the code outputs if the number is a prime or not.
Plan
- Input
- Check if prime
Input
num=int(input("Enter a number "))
The user inputs a number
Check if prime
x=2
flag=0
while flag==0 and x<=(math.sqrt(num)):
if (num%x)==0:
flag=1
x=x+1
if flag==0:
print('Prime')
else:
print('Not Prime')
This code checks all the numbers between 2 and square root of (chosen number) (inclusively) to check if the number has any factors. As soon as it finds a factor it stops checking (to save time and computing power). The code then displays whether the number is prime or not.
Full code
#Import
import math
#Input
num=int(input("Enter a number "))
#Check
x=2
flag=0
while flag==0 and x<=(math.sqrt(num)):
if (num%x)==0:
flag=1
x=x+1
if flag==0:
print('Prime')
else:
print('Not Prime')


