I have these functions that are intended to find all the prime divisors of every number from 2 to n:
from time import time
start = time()
primes = []
def primedivs1(n):
global primes
primedivs = []
a = n
for i in primes:
while not a % i:
primedivs.append(i)
a = a//i
if i * i > a:
break
if a > 1:
primedivs.append(a)
if a == n:
primes.append(n)
return primedivs
print([primedivs1(i) for i in range(2, 10000)]) # test
end = time()
and
from time import time
start = time()
primes = []
def primedivs2(n):
global primes
primedivs = []
a = n
for i in primes:
q, r = divmod(a, i)
while r == 0:
primedivs.append(i)
a = q
q, r = divmod(a, i)
if i * i > a:
break
if a > 1:
primedivs.append(a)
if a == n:
primes.append(n)
return primedivs
print([primedivs2(i) for i in range(2, 10000)]) # test
end = time()
print("Execution time 1: ", round(end - start, 2), "s")
In my original function, primedivs1, for each n, the function has to perform division twice with a % i (I presume that to find the remainder, you have to find the quotient) and a = a//i. Thus, I made a small edit to primedivs1 and got primedivs2, which uses divmod and therefore only needs to do one division since the quotient is saved with divmod.
Why is primedivs2 actually slower than primedivs1? I thought that since division is computationally expensive, it should be the other way around.
Also, is there some alternative to divmod that does the same thing but is faster?