FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScriptTheAlgorithms/Maths/ModularArithmetic.js at master · run100/JavaScriptTheAlgorithms · GitHub
run100
/
JavaScriptTheAlgorithms
Public
forked from
TheAlgorithms/JavaScript
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScriptTheAlgorithms
/
Maths
/
ModularArithmetic.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
56 lines (48 loc) · 1.63 KB
Breadcrumbs
JavaScriptTheAlgorithms
/
Maths
/
ModularArithmetic.js
Copy path
File metadata and controls
56 lines (48 loc) · 1.63 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
}
*/
export
class
ModRing
{
constructor
(
MOD
)
{
this
.
MOD
=
MOD
}
isInputValid
=
(
arg1
,
arg2
)
=>
{
if
(
!
this
.
MOD
)
{
throw
new
Error
(
'Modulus must be initialized in the object constructor'
)
}
if
(
typeof
arg1
!==
'number'
||
typeof
arg2
!==
'number'
)
{
throw
new
TypeError
(
'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
}
}
Back
|
FazBrowse Home
|
New Git URL