i want to be able to make factorial while counting down

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jsmith27
    New Member
    • Jan 2015
    • 1

    i want to be able to make factorial while counting down

    Code:
    x = 5
    y = 5
    
    while x > 0:
        print (x, x * y)
        x -= 1

    how can i make this do factorial of 5?
    Last edited by bvdet; Jan 23 '15, 05:00 PM. Reason: Please use code tags when posting code [code]....[/code]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    There are several way to calculate a factorial of a number. This uses the built-in function reduce:
    Code:
    >>> import operator
    >>> reduce(operator.mul, range(5, 0, -1))
    120
    This uses recursion:
    Code:
    >>> def factorial(n):
    ... 	if n == 0:
    ... 		return 1
    ... 	return n*factorial(n-1)
    ... 
    >>> factorial(5)
    120
    >>>
    A simple for loop:
    Code:
    >>> x = 5
    >>> v = 1
    >>> for i in range(5, 0, -1):
    ... 	v *= i
    ... 	
    >>> v
    120
    >>>
    Choose what is best for your application.

    Comment

    Working...