Factorial for a non-negative integer or number is the multiplication of all positive integers less than or equal to the value. For example factorial for a 5 is 5x4x3x2x1 = 120. This is a part of **Data Structure.**

The above calculation is achieve by the formula of** ‘n!’** which can be represent as below. This is the mathematics formula which multiple the less values upto 1 of given position-integer.

```
n! = n x (n-1) x (n-2) x (n-3) x ....... x 1
Example: Factorial of 5
5! = 5x4x3x2x1
ans: 120
```

## Algorithm For getting Factorial of a number Examples

## Example1

Traverse the loop upto n. Simply traverse the array and multiply each value with new one. After completing the loop final answer will be saved in the answer. The result will be a BigInt type.

Below is the example of getting Factorial of a number in JavaScript.

```
function factorial(N)
{
// Initialize result
let n = BigInt(1); // Or BigInt 1
// Multiply n with 2, 3, ...N
for (var i = 2; i <= N; i++)
n *= BigInt(i);
return n;
}
// calling the function
let number = 20;
console.log(factorial(number));
result: 2432902008176640000
```

## Example 2

Let’s create a factorial program using a **recursive** function. Recursive function calls itself until the value is not equal to zero. It can be calculated using the below formula.

## JavaScript

```
function factorial(n){
if(n == 0){
return 1;
}
return n * factorial(n-1);
}
console.log(factorial(5))
```

**Time Complexity**: O(n)**Auxiliary Space**: O(n)

## Java

Below is the Java implementation for the factorial approach. We created a static method inside the class which is integer return type. It calls itself until the n’s value does not become zero.

```
class Test {
static int factorial(int n){
if(n == 0){
return 1;
}
return n * factorial(n-1);
}
public static void main(String[] args) {
int val = factorial(5);
System.out.println("Factorial is : " + val);
}
}
```

Answer:

Factorial is : 120

**Time Complexity**: O(n)**Auxiliary Space**: O(n)

See More example:

**Can You Spirally Rotate A Matrix Using Data Structure?**

You can comment in the comment section below for any doubt or query. Thank you for visiting **FlutterTPoint**.