algorithm - 求阶乘 n 模 m 比 O(n) 更快

标签 algorithm math factorial

如何找到比 On) (n!) % m 更快的内容?

1 <= n <= 1e18

1 <= m <= 1e6

最佳答案

您可以轻松拥有O(m)最坏情况下的时间复杂度(当 m 是素数时)并且它似乎足够好,因为你有 m <= 1e6 (而 n 可以达到 1e18 )。请注意,当 n >= m

 n! = 1 * 2 * ... * m * ... * n
                    ^
         factorial is divisible by m

这就是原因

 n! % m == 0       # whenever n >= m

另一个实现细节是您不必计算 n! % m1 * 2 * ... * n % m但你可以这样做 ((..(1 % m) * 2 % m) ... * n % m)为了不处理大量的数据。

C#代码示例

private static int Compute(long n, long m) {
  if (n >= m)
    return 0;

  long result = 1;

  // result != 0 - we can well get 0 and stop looping when m is not prime 
  for (long d = 2; d <= n && result != 0; ++d) 
    result = (result * d) % m;

  return result;
}

关于algorithm - 求阶乘 n 模 m 比 O(n) 更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72246366/

相关文章:

math - CAS - 二叉树替代方案

ruby-on-rails - Ruby on Rails 上的正态分布随机变量

python - 什么数据科学编程算法类似于连续变量的朴素贝叶斯?

algorithm - 为什么广度优先搜索有两个列出的时间复杂度?

确定加权图中最佳路径的算法

algorithm - 匹配算法效率

Java:关于弧度、Math.cos、Math.sin、double和long的问题

c - 错误消息 "format ‘%ld’ 需要类型为 ‘long int’ 的参数,但参数 2 的类型为 ‘int’“

java - 显示50!在 java

java - Java 中使用 BigInteger 计算 50 阶乘