当我将我的解决方案提交给 codechef 时,我不断收到时间限制错误。我从扫描仪切换到缓冲阅读器,但这并没有解决它。我认为它在我的算法中,但我不确定在哪里,除了检查每 5 个减量之外可能是不必要的。我找到的问题在哪里,以便我找出解决方法?
这是供引用的链接:https://www.codechef.com/problems/FCTRL
这是我的代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Factorial {
public static void main(String[] args) throws IOException {
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
//how many numbers follow
int number = Integer.parseInt(keyboard.readLine());
//stores zSum's to output later
int[] answerArray = new int[number];
for(int i = 0; i < number; i++) {
//the number to compute factorial
int n = Integer.parseInt(keyboard.readLine());
// moves number to one ending in 5
n -= n % 5;
//stores number of zeros
int zSum = 0;
for (int j = n; j > 0; j -= 5) {
//if a power of 5, add 1 to zSum
for (int k = 5; k <= j; k *= 5) {
if (j % k == 0) {
zSum ++;
}
}
}
answerArray[i] = zSum;
}
//println all values in array
for (int i = 0; i < number; i++) {
System.out.println(answerArray[i]);
}
}
}
最佳答案
你的复杂度太高了,
for (int j = n; j > 0; j -= 5)
将执行 O(N) 次操作。内部循环将增加对数的复杂性。 你应该写使用一些其他的方法。对于每个测试用例,它可以使用 O(log(N)) 时间来完成。
关于java - 我不确定为什么要为 codechef 获取 TLE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880892/