algorithm - 如何高效地统计[start,end]之间质因数只有3或5的数字?

标签 algorithm data-structures

在编码评估中,我遇到了这个问题,其中运行时的超时限制为 10 秒。问题要求返回只能被 3 或 5 整除且不能被任何其他数字整除的数字的计数,我对如何有效地解决它感到有点困惑。

这基本上是我尝试过的:

count = 0
for num in start...end:
   while num % 3 == 0: num /= 3
   while num % 5 == 0: num /= 5
   if num == 1:
      count += 1

最佳答案

所有解的形式都是3^x * 5^y。我们将考虑每个y值的结果。我们首先找到具有有效结果的最大 y 值,然后查看 x 的哪些对应值产生高于 start 的最小乘积> 及以下 endx 的两个值之间的差值就是该 y 值的有效结果数。然后我们递减y并将乘积除以5,并检查是否可以通过增加x的值使乘积回到范围内。依此类推...即使对于大范围,这最多也需要几十次计算。

如果您想保持简单并坚持整数算术并避免对数等昂贵的运算,您可以这样做:
(它在常规整数范围的时间限制内舒适地计时,但我还没有尝试过使用大整数。)

function factors3and5(start, end) {
    var fives = 0;
    var threesMin = 0, threesMax = 0;
    var productMin = 1, productMax = 1;
    var count = 0;

    while (productMax < end) {
        ++fives;
        productMax *= 5;
    }
    productMin = productMax;

    while (fives-- > 0) {
        productMin /= 5;
        productMax /= 5;
        while (productMin <= start) {
            ++threesMin;
            productMin *= 3;
        }
        while (productMax * 3 < end) {
            ++threesMax;
            productMax *= 3;
        }
        count += threesMax - threesMin + 1;
    }
    return count;
}
document.write(factors3and5(12345, 111222333444555)); // 288

关于algorithm - 如何高效地统计[start,end]之间质因数只有3或5的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76076987/

相关文章:

algorithm - 在两个排序数组的合并数组中查找中位数

matlab - 在 Matlab 中创建更复杂的数据结构?

algorithm - 存储间隔并允许快速删除的数据结构?

php - 我在 php 中寻找比 substr_count($string, $needle, $offset, $length) 更好的算法复杂度

firebase - 有没有办法在父文档不为空的情况下在 Firestore 中添加自定义路径子集合?

java - 创建 remove() 方法以从数组列表中删除项目 (Java)

c++ - AVL TREE - 按位置打印值的最有效方法。 C++

找到最小矩形数的算法

algorithm - 如何使用输入输出数据制作猜测函数的算法

python - 解决给定建筑物高度积水问题的算法