简体   繁体   中英

What is the fastest way to find the exact value of the factorial of a large number in python?

I'm aiming at particularly large values of the number whose factorial is to be found for example- 12345678!. Even math.factorial(12345678) in python takes a lot of time to compute the factorial of such a number.

I tried Stirling's Appoximation to compute the same but it does not give the exact value. Is there any other method to compute the same?

EDIT 1: This is the preview of the code I tried to compute the trailing zeros in factorial of the number

import math

def main():
    total_cases = int(eval(raw_input()))

    for case in xrange(total_cases):
        number = int(eval(raw_input()))

        if number >= 1e9:
            break

        factorial_n = math.factorial(number)

        count = 0

        for i in xrange(1, number):
            temp = 10**i

            if factorial_n % temp == 0 :
                count += 1
            else:
                print count
                break

main()

EDIT 2: I just found that the bottleneck is the dividing step.

scipy has a fast C implementation for both an approximation and exact values.

scipy.misc.factorial(12345, exact=True)

Tried this myself, takes under a second.

But upon trying math.factorial(12345) it also takes under a second. Have you tried this yourself?

    def factorial(n):
        result = 1
        for i in range (1, (n +1)):
            result = i * result
        return result
    
    print (factorial (100))

This code computes the factorial of a number by using range function and for loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM