Optimization of Factorial Function
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.