c# – 手动修改数字的快捷方式

栏目: C# · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/987968/fast-way-to-manually-mod-a-number

我需要能够为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;
    }

但这需要很长时间.是否有任何简单快速的方法来执行此操作,而无需实际使用b AND的功能而不使用耗时的循环?如果所有其他方法都失败了,我可以创建一个bool数组来表示一个巨大的数据类型,并找出如何使用按位运算符来实现这一点,但必须有一个更好的方法.

我猜你在寻找: http://en.wikipedia.org/wiki/Montgomery_reduction

或者基于Modular Exponentiation的简单方法(来自维基百科)

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;
}

翻译自:https://stackoverflow.com/questions/987968/fast-way-to-manually-mod-a-number


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Flexible Pattern Matching in Strings

Flexible Pattern Matching in Strings

Gonzalo Navarro、Mathieu Raffinot / Cambridge University Press / 2007-7-30 / USD 64.99

String matching problems range from the relatively simple task of searching a single text for a string of characters to searching a database for approximate occurrences of a complex pattern. Recent ye......一起来看看 《Flexible Pattern Matching in Strings》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具