问题
I'm using the .NET BigInteger class to perform some math operations. However the ModPow method is giving me the wrong results. I have compared it to Java which I think is correct:
// C#
var a = new BigInteger(-1);
var b = new BigInteger(3);
var c = new BigInteger(5);
var x = BigInteger.ModPow(a, b, c); // (x = -1)
// Java
BigInteger a = new BigInteger("-1");
BigInteger b = new BigInteger("3");
BigInteger c = new BigInteger("5");
BigInteger x = a.modPow(b, c); // (x = 4)
Is it a bug in the .NET class or am I doing something wrong?
回答1:
It's just a matter of definitions. From MSDN on C#:
The sign of the value returned by the modulus operation depends on the sign of dividend: If dividend is positive, the modulus operation returns a positive result; if it is negative, the modulus operation returns a negative result. The behavior of the modulus operation with
BigInteger
values is identical to the modulus operation with other integral types.
And from the JavaDocs for mod:
This method differs from
remainder
in that it always returns a non-negativeBigInteger
.
For more info, see http://en.wikipedia.org/wiki/Modulo_operation#Remainder_calculation_for_the_modulo_operation.
来源:https://stackoverflow.com/questions/16884221/c-sharp-biginteger-modpow-bug