New update is available. Click here to update.

Last Updated: 1 Feb, 2021

Difficulty: Moderate

```
The first line contains a single integer ‘T’ denoting the number of test cases.
Each test case contains a single line with a single integer ‘N’ denoting the given number.
```

```
For each test case, print a string denoting the factorial of the given number in a separate line.
```

```
You do not need to print anything; it has already been taken care of. Just implement the given function.
```

```
1 <= T <= 50
1 <= N <= 500
Time Limit: 1 sec.
```

Since the factorials of large integers exceed 10^18 they cannot be stored in any variable of primitive data type, hence the idea is to use an array to store the factorial of the numbers.

**Steps are as follows:**

- In order to store the factorial of a number, we create a “result” array/list in which at each index we will store exactly one digit. To calculate the factorial of ‘N’ we need to multiply all numbers from 1 to N which means we need to run a loop from 2 to ‘N’ and multiply each integer.
- Let’s define a helper function to multiply an integer ‘X’ with the number represented by the “result” array. This function uses simple calculations to perform the multiplication.
- Firstly initialise a variable “carryOver” as 0.
- For all the digits in the result array do the following step.
- Let's say we are at the i'th digit of the multiplicand.
- value = result[i]*x+carryOver.
- result[i] = product mod 10.
- carryOver = product / 10.

- Let's say we are at the i'th digit of the multiplicand.
- Here, what we were doing is we one by one multiplying ‘X’ with every digit of “result”. The multiplication is done from the rightmost digit to the leftmost digit. If we store digits in the same order in “result”, then it becomes difficult to update the "result" array without extra space. Hence, “result” is maintained in the reverse way, i.e., digits from right to left are stored.
- Now run a loop until “carryOver” is not equal to 0.
- Insert (carryOver % 10) at the end of the multiplicand array and in each iteration update carryOver = carryOver / 10.

SIMILAR PROBLEMS

Longest Palindromic Substring

Posted: 4 Sep, 2022

Difficulty: Moderate

Cakes

Posted: 23 Sep, 2022

Difficulty: Easy

1-3 Palindrome

Posted: 4 Oct, 2022

Difficulty: Easy

Merge Two Sorted Arrays Without Extra Space

Posted: 19 Nov, 2022

Difficulty: Moderate

Co-Prime

Posted: 14 Dec, 2022

Difficulty: Hard

Popular Interview Problems: