Skip to content

Commit

Permalink
Modular Inverse: Fix modular bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
manrajgrover committed Nov 11, 2017
1 parent eafc83a commit 38fbcca
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/algorithms/math/modular_inverse.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,44 @@
const exEuclidean = require('./extended_euclidean');
const fastExp = require('./fast_exp');


/**
* Calculates modular inverse of a number
* Calculates modular inverse of a number using Fermet's theorem
*
* @param {Number} a Number for which inverse needs to be found
* @param {Number} m Mod val
* @return {Number} Modular Inverse
*/
const modularInverse = (a, m) => {
const result = exEuclidean(a, m);
if (result.gcd !== 1) {
const fermetModularInverse = (a, m) => {
if (a === 0 || m === 0) {
return null;
}

console.log(result);

return (result.x + m) % m;
return fastExp(a, m - 2, m);
};

module.exports = modularInverse;

/**
* Calculates modular inverse of a number using Fermet's theorem
* Calculates modular inverse of a number
*
* @param {Number} a Number for which inverse needs to be found
* @param {Number} m Mod val
* @return {Number} Modular Inverse
*/
const fermetModularInverse = (a, m) => fastExp(a, m - 2, m);
const modularInverse = (a, m) => {
if (a === 0 || m === 0) {
return null;
}

const result = exEuclidean(a, m);

if (result.gcd !== 1) {
return null;
}

return (result.x + m) % m;
};

module.exports = fermetModularInverse;
module.exports = {
fermetModularInverse,
modularInverse
};

0 comments on commit 38fbcca

Please sign in to comment.