Tuesday, September 16, 2014

Small factorials


Problem

Idea : Given an integer n . You have to calculate n! . Very simple . Wait , the range of n from 1 to 100 . Using built in data type , you can calculate factorial up to 20 . Then ?

Now , you have to think something new . To face this situation , we can use array . In an array , we will keep a value . In every cell of the array , we will keep every digit of the value . Now think about calculating factorial as below -

                                         factorial = 1 ;
                                         for(int i=1;i<=n;i++)
                                         factorial*=i ;        // Multiplication to calculate factorial

For an array , we will multiply with array cell start from starting .

Initially we assign array[0] = 1 , and carry = 0 . Then for every value comes in the loop , we will multiply with every cell and add carry . Then the last digit of the value will remain in current position of the array . The carry is value/10 . After multiplying , we keep the carry infront of the array . Thus , if we iterate till n . We will get factorial in the array .


My Solution

No comments:

Post a Comment