Read the description of small factorials problem

small-factorials-problem-solving-in-c-solution-of-small-factorial-problem

Here in this small factorials problem we have to calculate factorial of a number. The user will given t numbers and we have to calculate the factorial of all these number where t is the testcase.

You may have think that we can do it very simply. But if you want to find the factorial of comparatively large number such as 70, then you will find that then result number is so big that we can not store it into any variable.

For this we have take an array to store such big number. However, this problem is taken from CodeChef for practice and learning purpose only. Here we will discuss the solution of this problem and see the code in C++.

Small factorials problem solving by C++

Suppose, you want to determine the factorial of 5.

Then 5! = 5 * 4 * 3 * 2

=  120

This is quite easy to determine. But if you think about the number 70.

Then 70! =11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000

Can you imagine the number? This is a very big number and we can not store it into any variable. But if we take an array to store this number then the problem will be solved.

Here in the bellow program we have implemented the logic to store the number inside an array. We will multiply the result one by one and store the result to the array. Let’s see the program bellow.

// solving small factorial problem

#include<iostream>
using namespace std;

int main(){
  int t;
  cin >> t;

  for(int i = 0; i < t; i++){
    int n;
    cin >> n;
    int size = 1000, nfact[size], carry = 0, j = size-1;
    nfact[size - 1] = 1;

    while(n > 1){
        int x;

        for(int k = size-1; k >= j; k--){
            x = nfact[k]*n + carry;
            nfact[k] = x % 10;
            carry = x / 10;
        }

        while(carry > 0){
            nfact[--j] = carry % 10;
            carry /= 10;
        }
        n--;
    }

    for(int k = j; k < size; k++){
        cout << nfact[k];
    }

    cout << endl;

  }

  return 0;

}

Output of this small factorials problem is given bellow;

4
1
1
2
2
5
120
3
6

First line of the output contains 4 which means we have to calculate the factorial of 4 numbers. Then each line contains an input and the bellow line gives the output. The factorial of 1 is 1. Similarly, 2! = 2, 5! = 120 and 3! = 6.

Previous pageTurbo sort

Next pageATM machine