Hello everyone, welcome to nkcoderz.com. In this article we will going to discuss about Python program to check whether the given number is prime or not.
C program to check whether the given number is prime or not
Table of Contents
Code for python program to check whether the given number is prime or not
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
# Test the function
print(is_prime(3))
Output
True
Explanation
The program defines a function is_prime
that takes an integer number as an argument num
and returns a boolean value indicating whether the number is prime or not.
The function first checks if the given number is less than 2, which is not considered prime numbers, it returns False. Next, it checks whether the given number is divisible by any number in the range 2 to num-1 (inclusive), if yes it returns False otherwise returns True.
You can test the function by calling it with any number as an argument, as shown in the last line of the code. This will print out True
if the number is prime and False
if it is not.
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5)+1):
if num % i == 0:
return False
return True
This method will be faster for large numbers as it reduces the number of iterations by checking only till square root of the given number.
Python program to find the square root of the given number without a square-root function
Conclusion
If you liked this post, then please share this with your friends and make sure to bookmark this website for more awesome content.