#---------------------------------------------------------------------- # Iterative vs. Recursive approaches to the same problem: computing # a factorial. The Factorial of integer N, written N!, is the product # of all integers from 1 up though N. For example, 4! = 1*2*3*4 = 24. # Copyright (C) November 1, 2017 -- Dr. William T. Verts #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Iterative approach. Run through all integers from 1 through N, # multiply those integers into result F. Note that 0! = 1. #---------------------------------------------------------------------- def Factorial1 (N): F = 1 for I in range(1,N+1): F = F * I return F #---------------------------------------------------------------------- # Recursive approach. Since 4! = 1*2*3*4, we can say that 4! = 4 * 3!, # or more generally N! = N * (N-1)! So, to compute any factorial, we # call Factorial with a smaller number, eventually reducing down to a # value that can be returned immediately. This is called "Divide and # Conquer". #---------------------------------------------------------------------- def Factorial (N): if N <= 1: return 1 else: return N * Factorial(N-1) #---------------------------------------------------------------------- # Factorial is almost always the first example in computer science # courses used to demonstrate recursion. In reality, the iterative # approach is almost always better for Factorial, but there are many # problems where recursion is exactly the appropriate solution. #----------------------------------------------------------------------