【问题标题】:C++: Counting zeros at the end optimizationC++:在优化结束时计数零
【发布时间】:2013-04-02 12:04:20
【问题描述】:

我正在尝试解决在任何自然数的阶乘末尾计算 0 的标准问题。我的代码工作正常,但在线判断给出“超出时间限制”错误。决定在这里询问我如何优化我的代码。

#include <iostream>

using namespace std;


int count (int n)
{
    int result = 0;
    for (unsigned int i = 5; i <= n; i += 5)
    {
        int temp = i;
        while (!(temp % 5))
        {
            ++result;
            temp /= 5;
        }
    }
    return result;
}



int main()
{
    int N;
    cin >> N;
    cin.get();
    for (unsigned int i = 0; i < N; ++i)
    {
        int n;
        cin >> n;
        cin.get();
        cout << count (n) << endl;
    }
    return 0;
}

提前致谢。

【问题讨论】:

  • 您可能需要stackoverflow.com/questions/11889999/… 之类的东西吗?
  • 您将 unsigned int 分配给 int。将所有 int 更改为 uint
  • 真的比将 int 分配给 int 或 unsigned int 分配给 unsigned int 需要更多时间吗?
  • @KudayarPirimbaev: intunsigned int 是“免费的”,因为按位表示按原样复制。令人惊讶的是,按位表示具有不同的含义,具体取决于您何时陷入只能由两者之一(通常为负值)表示的值。

标签: c++ algorithm optimization


【解决方案1】:

试试这个:

int count (int n)
{
    int result = 0;
    for (unsigned int i = 5; i <= n; i *= 5)
        result += n / i;
    return result;
}

1*2*..*N中,有N/5因子,可以被5整除。其中N/25 也可以被25 整除,...

【讨论】:

    【解决方案2】:

    您不必检查每个可被 5 整除的数字。相反,您可以用简单的系列数 5:

    count =  n div 5 + n div 25 + n div 125...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-14
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-26
      相关资源
      最近更新 更多