John-Michael
John-Michael

Reputation: 99

Difference in BigInteger calculations in C# and Python

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?

Upvotes: 2

Views: 136

Answers (1)

John-Michael
John-Michael

Reputation: 99

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

Upvotes: 2

Related Questions