21. Factorials of large numbers

21. Factorials of large number


Problem link :- click here


package programs;

import java.util.ArrayList;

public class Array__21
{

	static ArrayList<Integer> factorialOfLargeNumbers(int n)
	{
		ArrayList<Integer> product = new ArrayList<Integer>();
		
		//very important step I searched for this mistake for nearly 1 hour
		product.add(1);

		//multiplying from 2 because why do you multiply any number with 1
		for(int i=2; i<=n; i++)
		{
			//multiplying one by one
			multiply(product, i);
		}
		
		return product;
	}
	
	static void multiply(ArrayList<Integer> product, int multiplier)
	{
		int carry =0;
		for(int i=0; i<product.size(); i++)
		{
			//storing product with a digit(with carry added) in temporary variable
			int temp = (product.get(i) * multiplier)  + carry;
			
			//replacing that digit with unit place of the temporary variable
			//that's what we are supposed to do in our school days
			product.set(i, temp%10);
			
			//storing remaining in the carry
			carry = temp/10;
		}
		//placing the final carry in the new block
		while(carry!=0)
		{
			//placing from unit place carefully
			product.add( carry%10 );
			//updating carry
			carry = carry/10;
		}
	}
	
	public static void main(String[] args)
	{
		ArrayList<Integer> ans = factorialOfLargeNumbers(50);
		System.out.print("50!  =  ");
		for(int i=ans.size()-1; i>=0; i--)
			System.out.print(ans.get(i));
	}
}

Time complexity :- O(n)
Space complexity :- O(1)


Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree