I'm having troubles solving modulo in c#. The example below
7^-1 modulo 26
when on Wolfram Alpha returns correct 15. In c# when I tried direct:
1/7 % 26
it returns unwanted 0.142857142857143 instead of desired 15.
But i'm not a master mathematician, so i'm probably missing something vital.
Your are looking for modular inversion: in case of
or
you actually want to find out an
xsuch thatIn our case
x == 15sinceFor small
modulovalues (like26) you can find the answer (15) with a help of naiveforloop:In general case, you can obtain the
resultwith a help of Extended Euclid Algorithm. Often, when working with modulo arithmetics we face huge numbers, that's why let me show the code forBigInteger; if it's not your case you can turnBigIntegerto good oldint.Code:
The inversion itself will be
Demo:
Outcome: