Increase performance for finding Factorial of large numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rao121
    New Member
    • Sep 2020
    • 2

    Increase performance for finding Factorial of large numbers

    I am using iterative method and recursion method to implement factorial but when finding the same for large numbers,it takes alot of time.Any way to change that?
  • hussainmujtaba
    New Member
    • Apr 2020
    • 13

    #2
    I get your question , the problem of computing factorial has a highly repetitive structure. You can use dynamic programming to solve your problem. The conditions for implementing dynamic programming are
    • Overlapping sub-problems
    • optimal substructure


    Here is a code which may help you to understand what I am trying to say
    Code:
    def DPfact(N):
        arr={}
        if N in arr:
            return arr[N]
        elif N == 0 or N == 1:
            return 1
            arr[N] = 1
        else:
            factorial = N*DPfact(N - 1)
            arr[N] = factorial
        return factorial
        
    num=int(input("Enter the number: "))
    
    print("factorial of ",num," (dynamic): ",end="")
    print(DPfact(num))
    To get a more clear idea on factorial from basics to such advance level,
    Last edited by Rabbit; Sep 1 '20, 03:19 PM.

    Comment

    • rao121
      New Member
      • Sep 2020
      • 2

      #3
      Thankyou, It kinda helped

      Comment

      • SioSio
        Contributor
        • Dec 2019
        • 272

        #4
        The math module factorial implemented in C is faster than the recursive call.
        Code:
        import math
        num=int(input("Enter the number: "))
        print(math.factorial(num))

        Comment

        • dev7060
          Recognized Expert Contributor
          • Mar 2017
          • 655

          #5
          Here's the inbuilt factorial algorithm in case anyone's interested https://hg.python.org/cpython/file/7...module.c#l1218

          Comment

          Working...