c# - 手动修改号码的快速方法

标签 c# algorithm modulo

我需要能够为非常大的 a 和 b 值计算 (a^b) % c(它们分别插入极限,当您尝试计算 a^b 时会导致溢出错误)。对于足够小的数字,使用恒等式 (a^b)%c = (a%c)^b%c 是可行的,但如果 c 太大,这并没有多大帮助。我写了一个循环来手动执行 mod 操作,一次一个:

private static long no_Overflow_Mod(ulong num_base, ulong num_exponent, ulong mod) 
    {
        long answer = 1;
        for (int x = 0; x < num_exponent; x++)
        {
            answer = (answer * num_base) % mod;
        }
        return answer;
    }

但这需要很长时间。有没有简单快速的方法来执行此操作,而实际上不必使用 a 的 b 次方并且不使用耗时的循环?如果一切都失败了,我可以创建一个 bool 数组来表示一个巨大的数据类型,并找出如何使用位运算符来实现这一点,但必须有更好的方法。

最佳答案

我想您正在寻找:http://en.wikipedia.org/wiki/Montgomery_reduction 或基于模幂的更简单方法(来自维基百科)

Bignum modpow(Bignum base, Bignum exponent, Bignum modulus) {

    Bignum result = 1;

    while (exponent > 0) {
        if ((exponent & 1) == 1) {
            // multiply in this bit's contribution while using modulus to keep result small
            result = (result * base) % modulus;
        }
        // move to the next bit of the exponent, square (and mod) the base accordingly
        exponent >>= 1;
        base = (base * base) % modulus;
    }

    return result;
}

关于c# - 手动修改号码的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/987968/

相关文章:

c# - UserControl 的基类属于哪一层?

c# - 管理描述性 URL

c# - 使用泛型 C# 反序列化动态 XML

algorithm - 如何从点列表中找到模式(线、圆……)?

algorithm - 什么是尾递归?

python - 模数符号在这里起什么作用?

c# - 从 C# 调用 Delphi 6 DLL 会导致不同的舍入?

java - 从展平 DFS 结构创建递归结构

方案:余数函数 - 违反合约

java - 为什么在 java src 中 Integer 类的 toString 方法中使用负 int 进行 mod 操作