mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-27 15:41:16 +08:00
Update euclideanAlgorithm.js (#207)
Method 2 is easy to evaluate or understand without using recursion stack!
This commit is contained in:
parent
c4458e9d42
commit
c00c689255
@ -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;
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user