+ 1
Shortest way to calculate the Factorial
What is the shortest way to calculate the factorial of a number without using any libraries. I just want to optimize my code. https://code.sololearn.com/c7m1MD6M4IsP/?ref=app
3 Réponses
+ 5
https://code.sololearn.com/c3eg8MvlATAf/?ref=app
https://code.sololearn.com/cOInw4yJq7wi/?ref=app
https://code.sololearn.com/c4phTP2wUQ3u/?ref=app
https://code.sololearn.com/cE7lXk0wwKMN/?ref=app
https://code.sololearn.com/cOfMIY803RdZ/?ref=app
https://code.sololearn.com/cj7pAcAEmqTm/?ref=app
https://code.sololearn.com/c4Q0rFUFxZIP/?ref=app
+ 3
This is how I did it in one of my programs.
def fact(x):
y=x
for m in range(x-1,1,-1):
y*=m
return y
+ 1
Pretty short already.
I would subtly tighten it like this:
n=1
for i in range(2, int(input())+1):
n *= i
print(n)
You could import the builtin tool:
from math import factorial
print(factorial(5))
Another method:
from functools import reduce
print(reduce(int.__mul__, range(1, 6)))
Recursion version with function:
def fact(n):
return 1 if n<2 else n*fact(n-1)
print(fact(5))