失去精度具体来说,我现在在做的计算如下上大数目计算
Math.Pow(1527768,7)%7281809;
我知道这个问题的答案是1010101
,然而,这并不是我收到了答案。我相信这是因为我在Math.Pow()
中失去了精确度。我知道BigInteger
,我知道这可行,但System.Numerics
在我正在使用的环境中不可用(我无法以任何方式更改环境,因此,现在假设BigInteger不在问题中)。
是否有任何其他方式来执行上述操作更准确的精度?
失去精度具体来说,我现在在做的计算如下上大数目计算
Math.Pow(1527768,7)%7281809;
我知道这个问题的答案是1010101
,然而,这并不是我收到了答案。我相信这是因为我在Math.Pow()
中失去了精确度。我知道BigInteger
,我知道这可行,但System.Numerics
在我正在使用的环境中不可用(我无法以任何方式更改环境,因此,现在假设BigInteger不在问题中)。
是否有任何其他方式来执行上述操作更准确的精度?
,如果你只希望做这样的操作,你需要找到一个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
变量变得非常高 编辑:实际上,如果效率是一个因素,通常会有更高效的方法
这可能不是最好的,但我想到了这一点。演示@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);
}
的[Math.Pow没有被正确计算]可能的复制(http://stackoverflow.com/questions/4297454/math-pow-is-not-calculating-correctly) –
@SamuilPetrov我看到这个问题和明显的答案暗示我无法使用BigInteger。 – Srb1313711
尝试无标记的解决方案http://stackoverflow.com/a/4297502/4108884 –