The factorial of a number is defined as the product of all positive integers from to :
It is important to remember that the factorial of zero is equal to one:
For example:
Notice that, for example
The factorial of a number can be computed either using a loop or using recursion. In the latter case, one should utilize the recursive formula:
Algorithm implementation
Read the input value of .
scanf("%lld",&n);Compute the factorial of a number res = n! = 1 \cdot 2 \cdot 3 \cdot ... \cdot n.
res = 1;
for(i = 1; i <= n; i++)
res = res * i;Print the answer.
printf("%lld\n",res);Algorithm implementation — recursion
The fact function computes the factorial of the number .
long long fact(long long n)
{
if (n == 0) return 1;
return fact(n - 1) * n;
}The main part of the program. Read the input value of .
scanf("%lld",&n);Compute and print the answer.
res = fact(n);
printf("%lld\n",res);Java implementation — recursion
import java.util.*;
public class Main
{
static long fact(int n)
{
if (n == 0) return 1;
return fact(n - 1) * n;
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
long res = fact(n);
System.out.println(res);
con.close();
}
}Python implementation — loop
Read the input value of .
n = int(input())Compute the factorial of a number res = n! = 1 \cdot 2 \cdot 3 \cdot ... \cdot n.
res = 1
for i in range(1,n+1):
res *= iPrint the answer.
print(res)Python implementation — recursion
The fact function computes the factorial of the number .
def fact(n):
if n == 0: return 1
return n * fact(n-1)The main part of the program. Read the input value of .
n = int(input())Compute and print the answer.
print(fact(n))