Check whether n is prime

Jimmy (xiaoke) Shen
1 min readDec 21, 2019

--

code is from above.

The first code has a bug (when n is 4 will give the wrong answer) and I fixed it. The fixed one is below:

def is_prime(num):
if num > 1:
for i in range(2, num//2+1):
if num%i==0:return False
return True
else:
return False
def is_prime(n) :

# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True

# This is checked so that we can skip
# middle five numbers in below loop
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

Or we can write the second one in a more concise way

def is_prime(n):
if n<=1:return False
if n==2 or n==3:return True
if n%2==0 or n%3==0:return False
for i in range(5, int(n**0.5)+1, 6):
if n%i==0 or n%(i+2)==0:return False
return True

866. Prime Palindrome

This problem is using this function to check whether a num is prime or not.

--

--

No responses yet