-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add invmod (modular multiplicative inverse) #2368
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks @thetazero, looks good and well tested. Two feedbacks:
- I made one inline comment
- Can you also add an entry with documentation in https://github.com/josdejong/mathjs/blob/develop/src/expression/embeddedDocs/embeddedDocs.js, so
math.help(math.invmod)
will work?
src/function/arithmetic/invmod.js
Outdated
a = a % b | ||
if (b === 0) throw new Error('Divisor must be non zero') | ||
let res = xgcd(a, b) | ||
if (config.matrix === 'Matrix') res = res._data |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The check config.matrix === 'Matrix'
is implicit, can you change this to either use isMatrix(x)
from /src/utils/is.js
and use .toArray()
or .valueOf()
on the Matrix instead of using it's private ._data
property? Or simply call res.valueOf()
which will return Array for every case (when res is Array, DenseMatrix, or SparseMatrix).
One more thought: I think it should be possible to merge the two implementations into one, using the generic functions like |
Really appreciate all of your feedback I think it all makes a lot of sense. |
Thanks for your updates. Ok so making a generic solution requires more work on fraction/bignumber. Makes sense to address that separately. I think all is ready, I only see that browser testing is failing on the NaN unit tests. Can you change these tests from |
I was confused about that browser test failing, thanks so much for figuring out what the issue was. I've updated the unit test to work now. |
Thanks, looks good. Yeah, NaN is a weird case but it sort of makes sense 😄 . |
Published now in |
Added invmod (modular multiplicative inverse)
Based off #1744
Test Cases based of the ones for xgcd, plus the addition of dealing with the non existence of a multiplicative inverse, and a zero modulus.
In this implementation it returns NaN if there is no multiplicative inverse, rather than throwing an error.
I think this is reasonable, but if you have another idea for how to handle that case let me know.