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