C# BigInteger.ModPow bug?

南笙酒味 提交于 2020-06-08 16:23:52

问题


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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!