DEV Community

Cover image for Factorial of a large Number
Tisha Agarwal
Tisha Agarwal

Posted on

Factorial of a large Number

Given an integer N, find its factorial.

Example 1:
Input: N = 5
Output: 120
Explanation : 5! = 1*2*3*4*5 = 120

Example 2:
Input: N = 10
Output: 3628800
Explanation :
10! = 1*2*3*4*5*6*7*8*9*10 = 3628800

To solve this question click here:(https://practice.geeksforgeeks.org/problems/factorials-of-large-numbers2508/1#);

Asked in companies like Adobe, BrowserStack, MakeMyTrip, Microsoft, Philips, Samsung

It is a MEDIUM LEVEL question, you must have calculated factorial of a number. But this question is a bit different, in this we have to calculate factorial of a large number.

Factorial of large numbers cannot be stored in int or long or long long. So in this case we use ArrayList or LinkedList to solve the question.

JAVA CODE

static ArrayList<Integer> factorial(int N){
        //code here
        ArrayList<Integer> res=new ArrayList<>();
        res.add(0,1); //adding 1 in the arraylist
        int size=1;
        int carry=0,val=2;

        while(val<=N)
        {
            for(int i=size-1;i>=0;i--)
            {
                int temp=res.get(i)*val + carry;
                //store the last digit at index and add remaining to carry
                res.set(i,temp%10);
                //update carry
                carry=temp/10;
            }
            while(carry!=0)
            {
                res.add(0,carry%10);
                carry=carry/10;
                size++;
            }
            val++;

        }
        return res;
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)