mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-08 19:06:00 +00:00
16 lines
515 B
JavaScript
16 lines
515 B
JavaScript
/**
|
|
* Recursive version of Euclidean Algorithm of finding greatest common divisor (GCD).
|
|
* @param {number} originalA
|
|
* @param {number} originalB
|
|
* @return {number}
|
|
*/
|
|
export default function euclideanAlgorithm(originalA, originalB) {
|
|
// Make input numbers positive.
|
|
const a = Math.abs(originalA);
|
|
const b = Math.abs(originalB);
|
|
|
|
// To make algorithm work faster instead of subtracting one number from the other
|
|
// we may use modulo operation.
|
|
return (b === 0) ? a : euclideanAlgorithm(b, a % b);
|
|
}
|