簡體   English   中英

大數計算失去精度

[英]Losing precision on big number calculations

具體來說,我現在正在做的計算如下

Math.Pow(1527768,7)%7281809;

我知道答案是1010101 ,但是,這不是我收到的答案。 我相信這是由於我在Math.Pow()失去精度的Math.Pow() 我知道BigInteger並且知道它可以工作,但是System.Numerics在我正在使用的環境中不可用(我無法以任何方式更改環境,因此,現在假設BigInteger不在考慮范圍之內)。

還有其他方法可以更精確地執行上述操作嗎?

如果您只是想進行這種操作,需要查找冪函數的模,則可以制作一個簡單的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變量變得很高,也有更有效的算法編輯:實際上,如果效率是一個因素,通常會有更有效的方法

這可能不是最好的方法,但是我想出了辦法。 演示@ 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM