1.辗转相除法
function commonDivisor1(num1,num2) {
if ((num1-num2) < 0) {
var k = num1;
num1 = num2;
num2 = k;
}
while (num2 !=0) {
var remainder = num1%num2;
num1 = num2;
num2 = remainder;
}
return num1;
}
2.更相减损法
function commonDivisor2(num1,num2) {
var index=0;
while (num1%2==0 && num2%2 ==0) {
num1 = num1/2;
num2 = num2/2;
index += 1;
}
if ((num1-num2) < 0) {
var k = num1;
num1 = num2;
num2 = k;
}
var cha = num1-num2;
while (cha != num2) {
if (cha -num2>0) {
num1 = cha;
} else {
num1 = num2;
num2 = cha;
}
cha = num1-num2;
}
if (index == 0) {
return cha;
} else {
return cha*index*2;
}
}