2017-04-26 31 views
0

失去精度具體來說,我現在在做的計算如下上大數目計算

Math.Pow(1527768,7)%7281809; 

我知道這個問題的答案是1010101,然而,這並不是我收到了答案。我相信這是因爲我在Math.Pow()中失去了精確度。我知道BigInteger,我知道這可行,但System.Numerics在我正在使用的環境中不可用(我無法以任何方式更改環境,因此,現在假設BigInteger不在問題中)。

是否有任何其他方式來執行上述操作更準確的精度?

+1

的[Math.Pow沒有被正確計算]可能的複製(http://stackoverflow.com/questions/4297454/math-pow-is-not-calculating-correctly) –

+0

@SamuilPetrov我看到這個問題和明顯的答案暗示我無法使用BigInteger。 – Srb1313711

+0

嘗試無標記的解決方案http://stackoverflow.com/a/4297502/4108884 –

回答

1

,如果你只希望做這樣的操作,你需要找到一個powerfunction的模數,你可以做類似下面

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

簡單modPow功能也有更高效的算法,如果power變量變得非常高 編輯:實際上,如果效率是一個因素,通常會有更高效的方法

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