Write A Python Function To Check Whether The Number Is Prime Or Not

Given an Integer number  as an input to the Python program.  the program should accept the integer and call a function check_prime() To check if the number is prime or not.

Prime number is a number that is only divisible by 1 and the number itself.

For example, let's take 5 as a number. 5 is completely  divisible by 1 and 5 only so 5 is a prime number.

Now let's take another example 22.  22 is completely divisible by 1, 2, 11, 22.  So 22 has four factors that can divide 22 completely so it's not a prime number.

 

Write A Python Function To Check Whether The Number Is Prime Or Not

 

 

Write A Python Function To Check Whether The Number Is Prime Or Not

Let's take a function check_prime() and pass the integer number as an input argument. Using the for loop iterates from 2 to the square root of number (i.e, number ^ 1/2) plus one.

Perform modulus operation by dividing the number by the range of values. if the number is completely divisible by Value then return the string saying number is not a prime.

Use the for loop else part and once the following completes return the string that is number is prime,  shown below.

def check_prime(n):
   for value in range(2, int(n ** (0.5)) + 1):
       if n % value == 0:
           return "Number is Not a Prime"
   else:
       return "Number is Prime"




In the main program take a variable number and using the input function call ask a user to enter a number and convert it into an integer.

Use the print statement and directly call the function check prime and print the return string value.

number = int(input("Enter a Number : "))
print(check_prime(number))




Complete program
===================

def find_prime(n):
   for value in range(2, int(n ** (0.5)) + 1):
       if n % value == 0:
           return "Number is Not a Prime"
   else:
       return "Number is Prime"


number = int(input("Enter a Number : "))
print(find_prime(number))





Output 1
=============

Enter a Number : 22
Number is Not a Prime




Output
============

Enter a Number : 11
Number is Prime




Output 3
===============

Enter a Number : 100
Number is Not a Prime




Conclusion
=============

Try running the program by yourself and give the random integer values and more than the result.

Comment below if you have any suggestions or queries related to the above program.




Post a Comment

0 Comments