Home > Programming, Technology > Find factorial of a given number

## Find factorial of a given number

Here I’m going to illustrate the method for finding the factorial of a given number(<100) programmatically, which is different from that of finding factorial using long, int, double etc., In this I’m going to use array to store each digit of solution.

Method:

The method I used in my code is similar to that of natural multiplication.

Let us assume that we have two numbers 43 and 25 to be multiplied. Here I’m considering 43 is kept in an array as digit ‘3’ 0th index and digit ‘4’ 1st index. Now I’m multiplying 25 with 0th index digit and adding temp(which is initially zero), we get the sum. Now find total sum%10 which gives the value to be stored at that index. i.e a[0]=5, temp=7. In the next iteration a[1]=7 temp=10

those two ‘1’ and ‘0’ digits are appended at the end of the array.

Resulting a[0]=5 a[1]=7 a[2]=0 a[3]=1

1075

Let me put it in an algorithmic way.

N //given input

temp=0 //initially

a[200] // array where the given input N is stored

m //stores number of digits in a given input

Repeat until n becomes 1

do

n–

a[index]=(a[index]*n+temp)%10

temp=(a[index]*n+temp)/10

done

while temp is not zero

do //the resultant is more than m digit number so increment m

m++

a[m]=temp%10

temp=temp/10

done

Here is the working code in online editor where you can give input and also check for output.

input should be given in the following way.

3                 — Which means number of inputs to follow

12

23

43