1 / 4
Jan 2010

i have solved the problem on Factorial , however i don't know how to submit the code i.e. which class should i use? I submitted the code using Main class and i got Time Limit Exceeded error
my code is :

import java.math.BigInteger;
public class Main
{
     public BigInteger factorial(BigInteger n)
    {
        if(n.compareTo(BigInteger.ONE)<=0)
            return new BigInteger("1");
        else
            return n.multiply(factorial(n.subtract(new BigInteger("1"))));
    }
    public static void main(String args[]) throws java.lang.Exception
    {
        int count=0;
        java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        BigInteger n1 = new BigInteger("10");
        Main m = new Main();
        int cases = Integer.parseInt(br.readLine());
        for(int i=0;i<cases;i++)
        {
            BigInteger n=new BigInteger(br.readLine());
             BigInteger fact=m.factorial(n);
             while(fact.divide(n1).compareTo(BigInteger.ZERO)>0)
             {
                 BigInteger y = fact.remainder(n1);
                 if(y.compareTo(BigInteger.ZERO)==0)
                 {
                 count++;
                 fact=fact.divide(n1);
                 }
                 else
                     break;
              }
            System.out.println(count);
            count = 0; 
        }
}
}
  • created

    Jan '10
  • last reply

    Jan '10
  • 3

    replies

  • 484

    views

  • 2

    users

You submitted your code correctly - it didn't say compile error! Time limit exceeded means your program took too long to run. If you had tested your program on some large test cases, you would know why (your code has to run all 100000 cases, each which could be 1000000000, in 6 seconds.)

ok , but i can't really figure out where the mistake is in the code , so can anyone please help me?

I'm afraid there isn't a mistake as such, your algorithm is simply too slow. You should be aiming for a solution which doesn't involve calculating the actual factorials at all.