首页 > 代码库 > 算法基础练习--最大公约数和最小公倍数

算法基础练习--最大公约数和最小公倍数

var gcd = function (n1,n2){ //最大公约数
if(n1 == n2 ){return n1;}


var bigger = 0;
var smaller = 0;
if(n1 > n2){bigger = n1;smaller = n2;}
else {bigger = n2;smaller = n1;}


for(var j = 1; j <= smaller ; j++){
if(smaller%(smaller/j) != 0){continue;}
if(bigger % (smaller / j) == 0){return smaller/j;}
}


return undefined;
}



//最小公倍数
var lcm = function (n1,n2){
if(n1 == n2){return n1;}
var bigger = 0;
var smaller = 0;
if(n1 > n2){bigger = n1;smaller = n2;}
else {bigger = n2;smaller = n1;}


for(var i = 2; i <= bigger; i++){
if(i * smaller % bigger == 0){ return i * smaller;}
}
return undefined;


}