Search code examples
c#bigintegermodulo

BigInteger.mod in java equivalent in c#


In java:

b1 = new BigInteger("-3896390610386937370574318634931111609708735540536209530871");
b2 = new BigInteger("1000000000000000000000000000000000000000");

// apply mod() method
BigInteger result = b1.mod(b2);

result = 425681365068888390291264459463790469129

While I am trying to write the same code in c# I am getting the other value

In C#

BigInteger b1 = 
BigInteger.Parse("-3896390610386937370574318634931111609708735540536209530871");
BigInteger b2 = BigInteger.Parse("1000000000000000000000000000000000000000");
BigInteger result = BigInteger.Remainder( b1, b2);

result = -574318634931111609708735540536209530871

I also tried with BigInteger % operator. I am not sure which method or operator to use to get the same value like in java.


Solution

  • You can write:

    b1 % b2 < 0 ? (b1 % b2) + b2 : b1 % b2;
    

    Wrap to your own method:

    public static int Mod(int b1, int b2)
    {
        var r = b1 % b2;
        return r < 0 ? r + b2 : r;
    }