2

Hi I'm trying to do some math on some BigInteger. I'm converting some code from Python to C# and the results I'm getting in C# compared to Python is different.

Here's the code in C#

BigInteger two = BigInteger.Parse("2");
BigInteger p = BigInteger.Parse("21888242871839275222246405745257275088548364400416034343698204186575808495617");
BigInteger s1 = BigInteger.Parse("14132513739920849383792069751007754351800355055139761101807090020635929082500");
BigInteger s2 = BigInteger.Parse("16855243938201383859390618757402894710090949997910827510175914850401122313679");

BigInteger result = BigInteger.ModPow((s1-s2) % p, p - two, p);

The result in C# is -172003418180865315706632281401673997799012376343679936021783339603882732265

In python

def calculateResult():
    two = 2
    p = 21888242871839275222246405745257275088548364400416034343698204186575808495617
    s1 = 14132513739920849383792069751007754351800355055139761101807090020635929082500
    s2 = 16855243938201383859390618757402894710090949997910827510175914850401122313679
    print(f'RESULT: { pow((s1 - s2) % p, p - two, p) }')

The result in python is 21716239453658409906539773463855601090749352024072354407676420846971925763352

Does anyone know what's going on here?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
John-Michael
  • 99
  • 1
  • 7
  • 2
    The result of a modulo in python is always positive. I imagine that's the crux of the issue here. – flakes Dec 11 '21 at 23:50
  • 1
    https://stackoverflow.com/a/3883019/3280538 – flakes Dec 11 '21 at 23:50
  • 1
    @flakes Mate, thank you so much for that link, I've been beating my brain over this for far too long. All I had to do was add the modulus to the result if it was negative! – John-Michael Dec 11 '21 at 23:59

1 Answers1

2

The solution was just to add the p value to the result if the sign of the number returned was negative!

if (result.Sign == -1)
{
  result = result + p;
}

See: https://stackoverflow.com/a/3883019/3280538

John-Michael
  • 99
  • 1
  • 7