Algorithm 阶乘尾随零BigO问题

Algorithm 阶乘尾随零BigO问题,algorithm,big-o,factorial,trailing,Algorithm,Big O,Factorial,Trailing,当我提交给leetcode时,它运行case 500/502,但失败了,原因:1808548329。但当我在自己的mac上运行它时,它给出了与公认的答案相同的答案 我的代码: int trailingZeroes(int n) { int count = 0; int tmp = 0; //check every number in [1, i] for (int i = 1; i <= n; i++) { tmp = i; whil

当我提交给leetcode时,它运行case 500/502,但失败了,原因:1808548329。但当我在自己的mac上运行它时,它给出了与公认的答案相同的答案

我的代码:

int trailingZeroes(int n) {
    int count = 0;
    int tmp = 0; //check every number in [1, i]
    for (int i = 1; i <= n; i++) {
        tmp = i;
        while (tmp % 5 == 0) {
            count++;
            tmp /= 5;
        }
    }
    return count;
}
它们在我的mac上运行相同的结果:

std::cout << trailingZeroes(1808548329) << std::endl; //452137076
std::cout << trailingZeroes2(1808548329) << std::endl; //452137076
第一个解决方案不被接受的原因是因为时间复杂性吗? 因为我在自己的mac上运行它,但它给出的答案与ac给出的答案相同

如何计算第一个解决方案的时间复杂度

是昂洛根吗?我不确定。你能帮我个忙吗-

已编辑,删除图片。

您的解决方案已打开

内部循环至少每5项重复一次 内部循环每25项至少重复两次 ... 内部循环每5^k个项目至少重复k次。 将其相加可得出内部循环运行:

n/5 + n/25 + n/125 + ... + 1 = 
n (1/5 + 1/25 + 1/125 + ... + 1/n)
这是,这是在

此外,如果忽略内部循环,则外部循环本身在迭代时具有相同的成本,因此这将保持启用状态


但是,另一种解决方案是在Ologn中运行,它的效率要高得多。

用文本替换图像。对不起,我是新手,它说,发布图片至少需要10个声誉。。我稍后会试试,谢谢。不要发布图片。相反,使用文本。把你的代码从你的编辑器复制到你的问题中。明白了,看起来好多了,谢谢。谢谢
n/5 + n/25 + n/125 + ... + 1 = 
n (1/5 + 1/25 + 1/125 + ... + 1/n)