Why is this code shown as wrong answer?

Contest Code:PRACTICE Problem Code:FCTRL2

/* package codechef; // don’t place package name! */

import java.util.;
import java.lang.
;
import java.io.*;

/* Name of the class has to be “Main” only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here

	Scanner s = new Scanner(System.in);
	int c = s.nextInt();//Input no of cases
	int n;//Number
	int ans;
	
	while(c > 0){
	    
	    n = s.nextInt();
	    ans = 1;
	    
	        while(n > 0){
	            ans = ans*n;
	            n--;
	        }
	        
	    System.out.println(ans);    
	    
	    
	    c --;
	}

}

}

1 Like

Hi mate,

You are asked to print the factorial of a digit <= 100. The range of integer in Java can not even store the factorial of 20. Since the number of digits in result are larger.

One possible way is to use Biginteger class from java, or you can implement basic multiplication paradigm which we use to do in our 1st-2nd class, by storing result and forwarding carry using array.

Thanks!
If you don’t mind, can you send the part of the code where you use BigInteger class?

but this prob is not intended to be solved by BigInteger class
think abt a different logic

1 Like
    int mul[100000]={};  /// result array

    int n;
    cin>>n;
    mul[0]=1;

    int carry=0;  // initially carry is 0
    int len=1;   

/* length of our final product is 1 since 1 is of 1 digit
in the below logic we are multiplying result array above with numbers from 2 to n.
For example 129 * 12 first multiplication will be carried out as 9*12 retaining remainder at first place (108) and forwarding carry (108) for next number. See implementation below. */

    for(int i=2;i<=n;i++)
    {

        for(int j=0;j<len;j++)
        {
            mul[j]*=i;
            mul[j]+=carry;
            carry=mul[j]/10;
            mul[j]%=10;
        }
        while(carry)   // carry is propagated until it becomes zero 
        {
            mul[len]=carry%10;
            carry/=10;
            len++;   // over all length of the answer will certainly increase.

        }


    }   // We have treated 0th index as ones place 1st index as tenth place and so on.


    for(int j=len-1;j>=0;j--)
        cout<<mul[j];
    cout<<endl;

The code is in C++. You can get intuition similar for Java.

I hope it helps.

I solved it using BigInteger and without using it
BigInteger :- https://www.codechef.com/viewsolution/24479887
without BigInteger:- https://www.codechef.com/viewsolution/24479824

But as I said you are expected to solve it without using any language specific libraries