I tried a question from a contest whose exact statement is like this:
Given a number N. The task is to find the unit digit of factorial of given
number N.
Input:
First line of input contains number of testcases T. For each testcase, there
will be a single line containing N.
Output:
For each testcase, print the unit digit of factorial of N.
Constraints:
1 <= T <= 1000
1 <= N <= 1018
and came up with following code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) throws IOException{
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(reader.readLine());
int i=0;
while(i<cases){
fact(Integer.parseInt(reader.readLine()));i++;
}
}
static void fact(int num){
int j,fact=1;
for(j=1;j<=num;j++){
fact=fact*j;
}
System.out.println(fact%10);
}
}
It gives right output when executed with custom inputs but when all test cases are tried it gives:"TIME LIMIT EXCEEDED. Optimise your code". I tried to use bufferedReader instead of Scanner class but to no effect. I could not find out how could I optimise this code further. Is there anything I am missing?