Optimization of Factorial Function This is a solution to the CodeHhef problem FCTRL2 where we are supposed to find the factorial of numbers up to 100. I have tried several techniques but I am always exceeding their time limit (1 second). Please help me optimize this code to make it execute faster.

    import java.math.BigInteger;
    import java.io.*;
    class Abc{
        public static void main(String[] args) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BigInteger fact=new BigInteger("1");
       // BigInteger inc=new BigInteger("1");
        String str=br.readLine();
        int n=Integer.parseInt(str);

        for(int i=0;i&lt;n;i++)
        {    String st=br.readLine();
            BigInteger number=new BigInteger(st);

            for(BigInteger bi = BigInteger.valueOf(1);bi.compareTo(number)&gt;=0;bi = bi.add(BigInteger.ONE))
            {
                fact=fact.multiply(bi); 
            }
            System.out.println(fact);
        }
    } 
   }
It is unclear what n and st are in your code and you are mixing things together which makes fixing your code harder.

I therefore suggest refactoring your code:


extract the factorial calculation in its own method, without all the string conversion and input reading stuff:

private static BigInteger factorial(int n) {
  BigInteger fact = new BigInteger("1");
  for (int i = 1; i &lt;= n; i++) {
    fact = fact.multiply(BigInteger.valueOf(i));
  }
  return fact;
}

adapt your main method accordingly


Once you have done that, you can start optimising the factorial method, for example by caching the results as you calculate them.