java - 我不确定为什么要为 codechef 获取 TLE

标签 java algorithm

当我将我的解决方案提交给 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/

相关文章:

Java - 获取当前 JAR 中的文件名列表

algorithm - 寻找一组点的旋转中心

algorithm - 返回数组中重复数字序列的索引

algorithm - 暴力数组遍历的复杂度

java - 对 Spring Rest API 的所有查询进行自定义验证

java - 为什么 BinaryGap 对于 Trailing_zeroes 不正确(n = 6 和 n = 328)

java - 在 Java/Swing 中,有没有办法合法地使用 "attempt to mutate in notification"?

java - TreeViewer 中类似节点的更新未正确进行

python - 在 Python 中高效地搜索字符串

java - 寻找回文的低效解决方案