Checks if a number is prime in python?

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')
2 is prime
25 is not prime

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s