+ 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

24th Jan 2020, 1:06 PM
Utkarsh Prajapati
Utkarsh Prajapati - avatar
3 ответов
+ 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
24th Jan 2020, 2:03 PM
Jannik Müller
Jannik Müller - avatar
+ 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))
24th Jan 2020, 1:44 PM
HonFu
HonFu - avatar