Factorial#1658

Factorial (Çözgüdiň düşündirişi)

The factorial of a number is defined as the product of all positive integers from to :

n! = 1 * 2 * … * (n - 1) * n

It is important to remember that the factorial of zero is equal to one:

0! = 1

For example:

1! = 1; \\ 2! = 1 * 2 = 2; \\ 3! = 1 * 2 * 3 = 6; \\ 4! = 1 * 2 * 3 * 4 = 24;

Notice that, for example

5! = (1 * 2 * 3 * 4) * 5 = 4! * 5; \\ 100! = (1 * 2 * … * 99) * 100 = 99! * 100; \\ n! = 1 * 2 * … * (n - 1) * n = (n - 1)! * n;

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:

fact(n) = \begin{cases} fact(n - 1) \cdot n, n > 0 \\ 1, n = 0 \end{cases}

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 *= i

Print 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))