DSA/algorithms/Python/number_theory/prime_number.py

21 lines
508 B
Python
Raw Normal View History

2022-08-15 16:06:27 +00:00
#TO CHECK WHETHER A NUMBER IS PRIME OR NOT
2022-08-15 16:11:37 +00:00
def isPrime(N):
2022-08-15 16:06:27 +00:00
2022-08-15 16:11:37 +00:00
for i in range(2, int(N**0.5) + 1):
if N%i==0:
return False
2022-08-15 16:06:27 +00:00
2022-08-15 16:11:37 +00:00
return True
2022-08-15 16:06:27 +00:00
2022-08-15 16:11:37 +00:00
# TIME COMPLEXITY - O(sqrt(N))
# EXAMPLES
# print(isPrime(3)) -> True
# print(isPrime(15)) -> False
# We are just checking till sqrt(N) as if their is any factor of a number
# greater than sqrt(N) then it's partner will be less than sqrt(N) as if a*b>N
# and a>=sqrt(N) then b<=sqrt(N) as if b>sqrt(N) then a*b>N.