Nonrecursive Factorial Algorithm and Implementation in python

Algorithm fact(n)
     input: Nonegative integer n
     output: Fibonacci value of n
     if n = 0
         return 1
     m ← 1
     k ← 1
     while n ≥ k do
           m ←  m * k
           k ← k + 1
      return m

Finally the Python implementation

>>> def fact(n):
…     if(n==0): return 1;
…     m = 1;
…     k = 1;
…     while(n >= k):
…             m = m * k;
…             k = k + 1;
…     return m;

>>> fact(1)
1
>>> fact(2)
2
>>> fact(3)
6
>>> fact(4)
24
>>>

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *