Last active
February 15, 2020 16:48
-
-
Save iconifyit/580d4ae1c9851bd91b3559ec848f56b0 to your computer and use it in GitHub Desktop.
30 Days of Algorithms : Euclid's Algorithm to find Greatest Common Divisor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Euclid's algorithm for Greatest Common Divisor. | |
* @param {int} m | |
* @param {int} n | |
* @returns {string|number} | |
* | |
* Given : 0 < n < m | |
* | |
* 1. Divide m by n. If the remainder is 0, GCD is n. | |
* 2. m <-- n, n <-- r | |
* 3. Repeat until r == 0 | |
*/ | |
const gcd = (m, n) => { | |
if (m < 0 || n < 0) return '`m` and `n` must be positive integers'; | |
m = Math.max(m, n); | |
n = Math.min(m, n); | |
while(true) { | |
let r = m % n; | |
if (r === 0) return n; | |
m = n; n = r; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a much more terse way to code this in ES6 but I wrote the above to make it easier to understand. Here is the more terse version: