Skip to content

Commit

Permalink
Update euclideanAlgorithm.js (trekhleb#207)
Browse files Browse the repository at this point in the history
Method 2 is easy to evaluate or understand without using recursion stack!
  • Loading branch information
vamshi9 authored and trekhleb committed Sep 18, 2018
1 parent c4458e9 commit c00c689
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/algorithms/math/euclidean-algorithm/euclideanAlgorithm.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,23 @@
* @param {number} originalB
* @return {number}
*/

/*Method 1: A bit Complex to understand*/
export default function euclideanAlgorithm(originalA, originalB) {
const a = Math.abs(originalA);
const b = Math.abs(originalB);

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;
}

0 comments on commit c00c689

Please sign in to comment.