|
| 1 | +import { extendedEuclideanGCD } from './ExtendedEuclideanGCD' |
| 2 | + |
| 3 | +/** |
| 4 | + * https://brilliant.org/wiki/modular-arithmetic/ |
| 5 | + * @param {Number} arg1 first argument |
| 6 | + * @param {Number} arg2 second argument |
| 7 | + * @returns {Number} |
| 8 | + */ |
| 9 | + |
| 10 | +export class ModRing { |
| 11 | + constructor (MOD) { |
| 12 | + this.MOD = MOD |
| 13 | + } |
| 14 | + |
| 15 | + isInputValid = (arg1, arg2) => { |
| 16 | + if (!this.MOD) { |
| 17 | + throw new Error('Modulus must be initialized in the object constructor') |
| 18 | + } |
| 19 | + if (typeof arg1 !== 'number' || typeof arg2 !== 'number') { |
| 20 | + throw new TypeError('Input must be Numbers') |
| 21 | + } |
| 22 | + } |
| 23 | + /** |
| 24 | + * Modulus is Distributive property, |
| 25 | + * As a result, we separate it into numbers in order to keep it within MOD's range |
| 26 | + */ |
| 27 | + |
| 28 | + add = (arg1, arg2) => { |
| 29 | + this.isInputValid(arg1, arg2) |
| 30 | + return ((arg1 % this.MOD) + (arg2 % this.MOD)) % this.MOD |
| 31 | + } |
| 32 | + |
| 33 | + subtract = (arg1, arg2) => { |
| 34 | + this.isInputValid(arg1, arg2) |
| 35 | + // An extra MOD is added to check negative results |
| 36 | + return ((arg1 % this.MOD) - (arg2 % this.MOD) + this.MOD) % this.MOD |
| 37 | + } |
| 38 | + |
| 39 | + multiply = (arg1, arg2) => { |
| 40 | + this.isInputValid(arg1, arg2) |
| 41 | + return ((arg1 % this.MOD) * (arg2 % this.MOD)) % this.MOD |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * |
| 46 | + * It is not Possible to find Division directly like the above methods, |
| 47 | + * So we have to use the Extended Euclidean Theorem for finding Multiplicative Inverse |
| 48 | + * https://github.com/TheAlgorithms/JavaScript/blob/master/Maths/ExtendedEuclideanGCD.js |
| 49 | + */ |
| 50 | + |
| 51 | + divide = (arg1, arg2) => { |
| 52 | + // 1st Index contains the required result |
| 53 | + // The theorem may have return Negative value, we need to add MOD to make it Positive |
| 54 | + return (extendedEuclideanGCD(arg1, arg2)[1] + this.MOD) % this.MOD |
| 55 | + } |
| 56 | +} |
0 commit comments