Factorial in python, [closed]

0

People, I'm new in the programming area, and doing exercises I came across the following question:

Make a program that calculates the factorial of a user-supplied integer. Ex.: 5!=5.4.3.2.1=120

How do I use pycharm to solve this?

    
asked by anonymous 22.10.2016 / 06:06

2 answers

2

For the factorial problem it is quite simple to solve using a recursive function:

def fatorial(n):
    if n<=1:
        return 1
    else:
        return n*fatorial(n-1)
    
22.10.2016 / 10:43
2

Well, there are several ways to solve your problem. Two very simple ways are using recursion and a simple loop:

def fat1(n):
    if n <= 1:
        return 1
    return n*fat1(n-1)

def fat2(n):
    resultado = 1
    for i in range(1, n+1):
        resultado *= i
    return resultado

Another option in a more functional style:

from functools import reduce
from operator import mul

def fat3(n):
    return reduce(mul, range(1, n+1), 1)
    
26.10.2016 / 13:40