Python Program to Check Prime Number
Given a positive integer, check if the number is prime or not. A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples of first few prime numbers are {2, 3, 5,
Examples:
Input: n = 11
Output: true
Input: n = 15
Output: false
Input: n = 1
Output: false
School Method :
def isPrime(n):
if n < = 1 :
return False
for i in range ( 2 , n):
if n % i = = 0 :
return False ;
return True
print ( "true" ) if isPrime( 11 ) else print ( "false" )
print ( "true" ) if isPrime( 14 ) else print ( "false" )
|
Output:
true
false
Time complexity of this solution is O(n)
Optimized School Method :
def isPrime(n) :
if (n < = 1 ) :
return False
if (n < = 3 ) :
return True
if (n % 2 = = 0 or n % 3 = = 0 ) :
return False
i = 5
while (i * i < = n) :
if (n % i = = 0 or n % (i + 2 ) = = 0 ) :
return False
i = i + 6
return True
if (isPrime( 11 )) :
print ( " true" )
else :
print ( " false" )
if (isPrime( 15 )) :
print ( " true" )
else :
print ( " false" )
|
Output:
true
false
Please refer complete article on Primality Test | Set 1 (Introduction and School Method) for more details!
Last Updated :
30 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...