greatest common divisor 最大公约数
有些语言有内置的 gcd 函数,js没有,手写一个!
这里使用【辗转相除法】来完成!
const getGcd = (a, b) => {
let ans = 0
if (a < b) {
;[a, b] = [b, a]
}
while (b) {
ans = a % b
a = b
b = ans
}
return a
}
console.log(getGcd(2, 4)) // 2
console.log(getGcd(8, 4)) // 4
console.log(getGcd(48, 32)) // 16
console.log(getGcd(48, 48)) // 48
精简一下
const getGcd = (a, b) => {
if (a < b) {
;[a, b] = [b, a]
}
while (b) {
;[a, b] = [b, a % b]
}
return a
}
console.log(getGcd(2, 4)) // 2
console.log(getGcd(8, 4)) // 4
console.log(getGcd(48, 32)) // 16
console.log(getGcd(48, 48)) // 48