patternpythonMinor
Determine all prime, palindrome string integers within a range
Viewed 0 times
allrangewithinpalindromedetermineintegersprimestring
Problem
I have written a program in Python 3x to determine all the prime, palindrome string integers in the range of two given numbers.
How can I make this program run faster, mainly optimizing my
from math import sqrt
def check_prime(n):
if n<2:
return False
for i in range(2,int(sqrt(n))+1):
if n%i == 0:
return False
else:
return True
for times in range(5):
a,b = map(int,input().split())
ct = 0
for n in range(a,b+1):
if str(n) == str(n)[::-1] and check_prime(n):
ct += 1
print(ct)How can I make this program run faster, mainly optimizing my
check_prime function so that it is faster than currently?Solution
One suggestion: That
So you can check
You get diminishing returns by adding more checks. I benchmarked the above at about 2x as fast as your original code.
sqrt is expensive, and you can eliminate it in a lot of common cases. For example: if any number except 2 is even, then it's not prime. Every second time you call check_prime, you're passing an even number. So you can check
n%2 before the loop, and eliminate that sqrt on half of your calls. You can extend this to check the first few primes explicitly, before starting your loop:def check_prime(n):
if n<2:
return False
if n%2==0:
return n==2
if n%3==0:
return n==3
if n%5==0:
return n==5
for i in range(7, int(sqrt(n))+1, 2):
if n%i == 0:
return False
return TrueYou get diminishing returns by adding more checks. I benchmarked the above at about 2x as fast as your original code.
Code Snippets
def check_prime(n):
if n<2:
return False
if n%2==0:
return n==2
if n%3==0:
return n==3
if n%5==0:
return n==5
for i in range(7, int(sqrt(n))+1, 2):
if n%i == 0:
return False
return TrueContext
StackExchange Code Review Q#71036, answer score: 4
Revisions (0)
No revisions yet.