I wrote this script to determine the first triangular number to have more than 500 factors (a project euler problem) and ran it on both python2.7 and python3.3. I expected them to take more or less the same time but python3 take more than twice the time that python2.7 does. What could be the reason behind this?
def highest_power(integer,prime):
i=0
while integer%prime**i==0:
i+=1
return i-1
def n_factors(integer):
number_of_factors=1
start=2
while integer>1 and integer>=start:
number_of_factors=number_of_factors*(highest_power(integer,start)+1)
integer=integer/start**highest_power(integer,start)
start+=1
return number_of_factors
def main(number_of_factors):
number_of_factors_list=[1,1] # Initialized with number of factors for m=1 and 2
m=3
while number_of_factors_list[-1]*number_of_factors_list[-2]<number_of_factors:
if m%2!=0:
number_of_factors_list.append(n_factors(m))
elif m%2==0:
number_of_factors_list.append(n_factors(m/2))
m+=1
return (m-2)*(m-1)/2
if __name__=='__main__':
print(main(500))
Here are their timings
$ time python2 script.py
real 0m12.787s
user 0m12.788s
sys 0m0.000s
$ time python3 script.py
real 0m27.738s
user 0m27.739s
sys 0m0.000s
I'm running this on ubuntu 13.10 64 bit, with the precompiled binaries of python2.7 and python3.3.
You are using integer division in Python 2, and floating-point division in Python 3. See if adding
from __future__ import division
to the script increases the runtime under Python 2.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments