Skip to content

Commit 1a089cc

Browse files
appgurueugithub-actions
and
github-actions
authored
merge: Fix GetEuclidGCD (TheAlgorithms#1068)
* Fix GetEuclidGCD Implement the actual Euclidean Algorithm * Replace == with === * Lua > JS * Standard sucks * Oops * Update GetEuclidGCD.js * Updated Documentation in README.md Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 7d40bb4 commit 1a089cc

File tree

2 files changed

+16
-27
lines changed

2 files changed

+16
-27
lines changed

DIRECTORY.md

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
* **Cellular-Automata**
1919
* [ConwaysGameOfLife](Cellular-Automata/ConwaysGameOfLife.js)
2020
* **Ciphers**
21+
* [AffineCipher](Ciphers/AffineCipher.js)
2122
* [Atbash](Ciphers/Atbash.js)
2223
* [CaesarsCipher](Ciphers/CaesarsCipher.js)
2324
* [KeyFinder](Ciphers/KeyFinder.js)

Maths/GetEuclidGCD.js

+15-27
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,20 @@
1-
/*
2-
Problem statement and Explanation : https://en.wikipedia.org/wiki/Euclidean_algorithm
3-
4-
In this method, we have followed the iterative approach to first
5-
find a minimum of both numbers and go to the next step.
6-
*/
7-
81
/**
9-
* GetEuclidGCD return the gcd of two numbers using Euclidean algorithm.
10-
* @param {Number} arg1 first argument for gcd
11-
* @param {Number} arg2 second argument for gcd
12-
* @returns return a `gcd` value of both number.
2+
* GetEuclidGCD Euclidean algorithm to determine the GCD of two numbers
3+
* @param {Number} a integer (may be negative)
4+
* @param {Number} b integer (may be negative)
5+
* @returns {Number} Greatest Common Divisor gcd(a, b)
136
*/
14-
const GetEuclidGCD = (arg1, arg2) => {
15-
// firstly, check that input is a number or not.
16-
if (typeof arg1 !== 'number' || typeof arg2 !== 'number') {
17-
return new TypeError('Argument is not a number.')
7+
export function GetEuclidGCD (a, b) {
8+
if (typeof a !== 'number' || typeof b !== 'number') {
9+
throw new TypeError('Arguments must be numbers')
1810
}
19-
// check that the input number is not a negative value.
20-
if (arg1 < 1 || arg2 < 1) {
21-
return new TypeError('Argument is a negative number.')
11+
if (a === 0 && b === 0) return undefined // infinitely many numbers divide 0
12+
a = Math.abs(a)
13+
b = Math.abs(b)
14+
while (b !== 0) {
15+
const rem = a % b
16+
a = b
17+
b = rem
2218
}
23-
// Find a minimum of both numbers.
24-
let less = arg1 > arg2 ? arg2 : arg1
25-
// Iterate the number and find the gcd of the number using the above explanation.
26-
for (less; less >= 2; less--) {
27-
if ((arg1 % less === 0) && (arg2 % less === 0)) return (less)
28-
}
29-
return (less)
19+
return a
3020
}
31-
32-
export { GetEuclidGCD }

0 commit comments

Comments
 (0)