Update euclideanAlgorithm.js (#207)

Method 2 is easy to evaluate or understand without using recursion stack!
This commit is contained in:
Vamshi Bachaneboina 2018-09-18 10:34:56 +05:30 committed by Oleksii Trekhleb
parent c4458e9d42
commit c00c689255

View File

@ -3,9 +3,23 @@
* @param {number} originalB * @param {number} originalB
* @return {number} * @return {number}
*/ */
/*Method 1: A bit Complex to understand*/
export default function euclideanAlgorithm(originalA, originalB) { export default function euclideanAlgorithm(originalA, originalB) {
const a = Math.abs(originalA); const a = Math.abs(originalA);
const b = Math.abs(originalB); const b = Math.abs(originalB);
return (b === 0) ? a : euclideanAlgorithm(b, a % b); return (b === 0) ? a : euclideanAlgorithm(b, a % b);
} }
/*Method 2: Easy to evaluate*/
export default function euclideanAlgorithm2(originalA, originalB) {
const a = Math.abs(originalA);
const b = Math.abs(originalB);
while(a != b){
[a,b] = a>b : [a-b, b] : [a, b-a]
}
return a || b;
}