fave77 / Mathball

A JavaScript library for Competitive Programming
https://fave77.github.io/Mathball-Docs/
MIT License
99 stars 49 forks source link

Modular Multiplicative Inverse #39

Closed nilshah98 closed 5 years ago

nilshah98 commented 5 years ago

Do the checklist before filing the issue:

NOTE: Provide a clear and concise description of the feature that needs to be added! Or if its a bug, then provide the necessary steps to reproduce it along with screenshots.

In many competitive coding questions it is required to get modulo multiplicative inverse of your answer with some other number, many a times, it's prime - 10^9+7. So, an added functionality to find modulo multiplicative inverse of two numbers.

Maybe a separate function, for when the numbers are prime, coprime, and have factors.

Links- Modular Multiplicative Inverse GFG

fave77 commented 5 years ago

[Function: M.modInverse(a, b)]

Validation:

Category: Mathematical Utilities

Indrajit1997 commented 5 years ago

@pbiswas101 For this we need to implement a power function with modulo M in O(log n) time. So, we have to build it as another function of MathBall. Is it okay to make an issue on Power function? .

fave77 commented 5 years ago

@Indrajit1997 Alright, you can raise an issue discussing its implementation as M.pow(a, b, m) with the last parameter being optional! So, that it can also be used as M.pow(a, b)

nilshah98 commented 5 years ago

@pbiswas101 For this we need to implement a power function with modulo M in O(log n) time. So, we have to build it as another function of MathBall. Is it okay to make an issue on Power function?

The modular multiplicative inverse can be implemented using Extended Euclid Theorem, which doesn't require any power function with modulo M.

Additionally, here are a few points for implementing modulo multiplicative inverse -

  1. First need to check whether the numbers are relatively prime or not, ie. having GCD 1.
  2. If GCD is 1, proceed to find the modular multiplicative inverse using Extended Euclid Theorem, which won't require any modulo power function.
  3. If GCD is anything other than 1, return 0, as 0 can never be a modulo multiplicative inverse of a number.

Example Output -

M.modInv(10,460) = 0;    /* 10,460 not relatively prime, so return 0 */
M.modInv(3,26) = 9;        /* 3,26 relatively prime, so return modulo multiplicative inverse */

Complexity for Extended Euclid as well as Fermat is both - O(Log m)

Validation -

PS: Add more validations, if any

devRD commented 5 years ago

Can I work on this ?

fave77 commented 5 years ago

@devRD You're assigned!