fastest algorithm for factorial

which is best way for calculating factorial of a number n of more than 5 digit.

loop method:

s=1
for i in range(1,n+1):
    s*=i

recursion method:

def fact(n):
    if n==1 or n==0:
        return 1
    else:
        return n*fact(n-1)

from math import factorial

The loop will definitely be faster as it avoids the overhead of the function calls i.e.use of stack to store calling functions that are waiting for recursion to terminate. Infact i have sometimes noticed that replacing a function by code in the main part speeds up program by almost 2-3 times. Best way to analyse this would be to submit both codes and see their relative performance for the "small factorials " question in easy section.

1 Like

i wanted it for ‘factorial’ question in easy section

i had tried
import math math.factorial(), but when i calculate it for 100000 and above it take more time in python

What do you want?

link text

check for this one
for more help lokk in this tutorial here link text

1 Like

best algorithm for ‘factorial’ question ,so that my code doesn’t exceed the given time