Python program to check prime number

Python program to check prime number

The program gets a number as input from the user and checks whether the given number is prime or not.

A prime number is a number that can be divided exactly itself and one. 

For example, consider number 7, 

7 divides only by 1 and 7. so it is a prime number. In other terms, the factors of 7 are 1 and 7 only. So a number having two factors, one and the number itself are called as prime numbers.

Now consider number 6,

The factors of 6 include 1, 2, 3, and 6. The factors don't obey the rule of prime numbers as it's having factors other than 1 and 6.

Sample input 0 :

5

Sample output 0 :

Prime number

Sample input 1 :

6

Sample output 1 :

Not a prime number

Sample input 2 :

1

Sample output 2 :

Neither prime nor composite

Procedure :

1. Start.

2. create a function to check if the number is prime

    => initialize a flag variable as 0.

    => loop from 2 to n/2.

        => check if the number is divisible by any number in between 2 and n/2.

        => if the number is divisible by any number from 2 to n/2, flip the flag variable to 1 and break the loop.

        => otherwise continue

    => if flag = 0

        => return true

    => if flag = 1

        => return false

3. Get the number as input from the user.

4. If the number is 1 => print neither prime nor composite

5. If the number is greater than 1 => Check if the number is prime or not using the function created.

6. Print the result.

7. End.


Code :

#function to check if the number is prime

def isPrime(n):

#initialize flag as 0

flag = 0

#divide the number from 2 to n/2

#if remainder is 0, then break (the number is not a prime number)

#if the number is not divisible by any of the number, then the number is a prime number

for i in range(2, int(n/2)+1):

if(n % i == 0):

flag = 1

break

else :

continue

if(flag == 0):

return True

else :

return False

#get the number from user

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

#number 1 is neither composite nor prime

if(num == 1):

print("The number is neither prime nor composite.")

elif(num > 0):

#check if the number is prime number using the isprime function

if(isPrime(num)):

print("The number is a prime number.")

else :

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

Output screenshot :

prime number in python




prime number in python



prime number in python



Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution