在大数字计算上失去精确度

时间:2017-04-26 09:46:56

标签: c# math mathematical-optimization

具体来说,我现在正在进行的计算如下:

Math.Pow(1527768,7)%7281809;

我知道答案是1010101,但是,这不是我收到的答案。我相信这是因为我在Math.Pow()中失去了精确度。我知道BigInteger并且我知道这有效,但System.Numerics在我正在使用的环境中不可用(我无法以任何方式改变环境,所以,现在,假设BigInteger已经不在问题)。

还有其他方法可以更精确地执行上述操作吗?

2 个答案:

答案 0 :(得分:1)

如果你只是想做这种操作,你需要找到一个功能函数的模数,你可以做一个简单的modPow函数,如下所示

static uint modPow(uint n, uint power, uint modulo)
{
    ulong result = n % modulo;
    for (uint i = power; i > 1; i--)
        result = (result * n) % modulo;
    return (uint)result;
}

如果power变量变得非常高,还有更有效的算法 编辑:实际上,如果效率是一个因素,通常会有更有效的方法

答案 1 :(得分:1)

这可能不是最好的,但我想到了这个。演示@ https://dotnetfiddle.net/Y2VSvN
注意 :该功能仅针对正数进行测试。

/// <summary>
/// Calculates the modulus of the power of a mutiple. 
/// </summary>
/// <param name="modularBase">Modulus base.</param>
/// <param name="value">Value to be powered</param>
/// <param name="pow">Number of powers</param>
/// <returns></returns>
static long GetModularOfPOW(int modularBase, int value, uint pow)
{
    return GetModularOf(modularBase, (pow > uint.MinValue) ? Enumerable.Repeat(value, (int)pow).ToArray() : new int[] { value });
}

/// <summary>
/// Calculates the modulus of the multiples. 
/// </summary>
/// <param name="modularBase">The modulus base.</param>
/// <param name="multiples">The multiples of the number.</param>
/// <returns>modulus</returns>
static long GetModularOf(int modularBase, params int[] multiples)
{
    /**
    * 1. create a stack from the array of numbers.
    * 2. take the 1st and 2nd number from the stack and mutiply their modulus
    * 3. push the modulus of the result into the stack.
    * 4. Repeat 2 -> 3 until the stack has only 1 number remaining.
    * 5. Return the modulus of the last remaing number.
    *
    * NOTE: we are converting the numbers to long before performing the arthmetic operations to bypass overflow exceptions.
    */
    var result = new Stack(multiples);
    while (result.Count > 1)
    {
        long temp = (Convert.ToInt64(result.Pop()) % Convert.ToInt64(modularBase)) * (Convert.ToInt64(result.Pop()) % Convert.ToInt64(modularBase));                
        result.Push(temp % modularBase);
    }

    return Convert.ToInt64(result.Pop()) % Convert.ToInt64(modularBase);
}