返回介绍

lcci / 16.05.Factorial Zeros / README_EN

发布于 2024-06-17 01:04:43 字数 2517 浏览 0 评论 0 收藏 0

16.05. Factorial Zeros

中文文档

Description

Write an algorithm which computes the number of trailing zeros in n factorial.

Example 1:


Input: 3

Output: 0

Explanation: 3! = 6, no trailing zero.

Example 2:


Input: 5

Output: 1

Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

Solutions

Solution 1: Mathematics

The problem is actually asking for the number of factors of $5$ in $[1,n]$.

Let's take $130$ as an example:

  1. Divide $130$ by $5$ for the first time, and get $26$, which means there are $26$ numbers containing a factor of $5$.
  2. Divide $26$ by $5$ for the second time, and get $5$, which means there are $5$ numbers containing a factor of $5^2$.
  3. Divide $5$ by $5$ for the third time, and get $1$, which means there is $1$ number containing a factor of $5^3$.
  4. Add up all the counts to get the total number of factors of $5$ in $[1,n]$.

The time complexity is $O(\log n)$, and the space complexity is $O(1)$.

class Solution:
  def trailingZeroes(self, n: int) -> int:
    ans = 0
    while n:
      n //= 5
      ans += n
    return ans
class Solution {
  public int trailingZeroes(int n) {
    int ans = 0;
    while (n > 0) {
      n /= 5;
      ans += n;
    }
    return ans;
  }
}
class Solution {
public:
  int trailingZeroes(int n) {
    int ans = 0;
    while (n) {
      n /= 5;
      ans += n;
    }
    return ans;
  }
};
func trailingZeroes(n int) int {
  ans := 0
  for n > 0 {
    n /= 5
    ans += n
  }
  return ans
}
function trailingZeroes(n: number): number {
  let ans = 0;
  while (n > 0) {
    n = Math.floor(n / 5);
    ans += n;
  }
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文