I wrote a function to know whether a number is prime in Python (using Python 3.8.1 in this case). See is_prime_v1 below. Then I thought of trying a v2 by using the any built-in function, see is_prime_v2 below. I was curious to know the time difference between v1 and v2, and with the code below I get the following output on my computer:
v1: 5.224290132522583
v2: 7.654775142669678
Which surprises me. I would have assumed that making use of any would take about the same time or even be faster. But here it's slower, a guess could be that it's due to the function call to any itself, but I'm unsure. Maybe someone with deeper Python knowledge could explain why?
from time import time
from math import sqrt
def is_prime_v1(n):
if n < 3 or n % 2 == 0:
return n == 2
for i in range(3, int(sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def is_prime_v2(n):
if n < 3 or n % 2 == 0:
return n == 2
return not any(n % i == 0 for i in range(3, int(sqrt(n)) + 1, 2))
if __name__ == '__main__':
RANGE_SIZE = 2000000
t = time()
for i in range(RANGE_SIZE):
is_prime_v1(i)
print('v1:', time() - t)
t = time()
for i in range(RANGE_SIZE):
is_prime_v2(i)
print('v2:', time() - t)
n % i == 0 for i in range(3, int(sqrt(n)) + 1, 2)slow things down. They are essentially equivalent to your regular loop but with overhead