DEV Community

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

Posted on

3 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay