![](/img/trans.png)
[英]I am writing a code for CodeChef. but getting error TLE is it possible to optimize it more?
[英]I am not sure why I am getting a TLE for codechef
当我将解决方案提交给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]);
}
}
}
您的复杂性很高,
对于(int j = n; j> 0; j-= 5)
将执行O(N)运算。 内部周期将增加日志的复杂性。 您应该使用其他方法编写。 可以使用每个测试用例的O(log(N))时间来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.