简体   繁体   中英

C# BigInteger.ModPow bug?

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?

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-negative BigInteger .

For more info, see http://en.wikipedia.org/wiki/Modulo_operation#Remainder_calculation_for_the_modulo_operation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM