2017-04-26 15 views
0

は具体的には、私が今やっている計算は、私はこれに対する答えは1010101知っている次大きな数の計算上の精度を失う

Math.Pow(1527768,7)%7281809; 

は、しかし、これは私が受けています答えではありません。これは、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変数が非常に高くなる EDIT:効率が因子の場合は、実際には効率的な方法が一般的です。

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); 
} 
関連する問題