I am not a mathematician, nor a computer scientist - just a hobbyist programmer and I am trying to teach myself Python by doing the Euler Project problems. One of them requires the use of a factorial. I wrote my own calculation using a recursive function and then realised that there was probably a built-in function which I could use. Having found it I thought I would see how much quicker it was than my recursive function. To my surprise I find that it is actually slower.
Does this surprise anyone? I am just curious.
I enclose my code (and for good measure I have also included a loop method for an extra comparison).
import math
import time
x = 50
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
secs = time.clock()
print(math.factorial(x))
print ("The built-in function took {a:0.5f} seconds.".format(a = time.clock() - secs))
secs = time.clock()
print (factorial(x))
print ("The recursive function took {a:0.5f} seconds.".format(a = time.clock() - secs))
secs = time.clock()
factl = 1
for i in range (1,x+1):
factl *= i
print (factl)
print ("The loop method took {a:0.5f} seconds.".format(a = time.clock() - secs))
Output:
30414093201713378043612608166064768844377641568960512000000000000
The built-in function took 0.00549 seconds.
30414093201713378043612608166064768844377641568960512000000000000
The recursive function took 0.00299 seconds.
30414093201713378043612608166064768844377641568960512000000000000
The loop method took 0.00259 seconds.