Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 630
nefarel Avatar asked Jun 02 '13 15:06

nefarel


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Why do we write C?

We write C for Carbon Because in some element the symbol of the element is taken form its first words and Co for Cobalt beacause in some elements the symbol of the element is taken from its first second letters, so that the we don't get confuse.


1 Answers

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.

like image 89
Oliver Charlesworth Avatar answered Sep 21 '22 08:09

Oliver Charlesworth