Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

factorial of large number

class Solution {
public:
    #define pb push_back
    void multiply(vector<int>& arr, int no){
        int carry = 0;
        
        // Multiply each digit with the correspomding no, like in simple maths of mult.
        for(int i=0;i<arr.size();i++){
            int prod = arr[i] * no + carry;
            arr[i] = prod % 10;
            carry = prod / 10;
        }
        
        // If carry is sill there
        while(carry){
            arr.pb(carry % 10);
            carry = carry / 10;
        }
    }
    
    vector<int> factorial(int n){
        // code here
        vector<int>arr = {1};
        
        // 5! = 5*4*3*2*1
        // The crux here is how to multiply two numbers if it is large
        for(int i=2;i<=n;i++){
            multiply(arr, i);
        }
        
        // print the array or return the array
        reverse(arr.begin(), arr.end());
        
        return arr;
    }
};
 
PREVIOUS NEXT
Tagged: #factorial #large #number
ADD COMMENT
Topic
Name
3+1 =