Open nunnly opened 9 years ago
function LCM() {
this.common = {};
this.members = {};
for (var i = 0; i < arguments.length; i++) {
this.members[arguments[i]] = [];
this.divide(arguments[i]);
this.stats(arguments[i]);
}
this.assimilate();
}
LCM.prototype = {
constructor: LCM,
divide: function (key) { // 求出key的所用最小余数
var i = 2, number = key,
divisor = this.members[key];
while (number >= 2) {
if (number % i === 0) {
divisor.push(i);
number = number / i;
i = 1;
}
i++;
}
},
stats: function (key) { // 统计每个最小余数的数量
var divisor = this.members[key], i = 0, keys = {};
for (i; i < divisor.length; i++) {
if (keys[divisor[i]]) {
keys[divisor[i]]++
} else {
keys[divisor[i]] = 1;
}
}
this.members[key] = keys;
},
assimilate: function () { // 统计所有数对应的最小余数的最大数
var common = this.common,
key, i, divisor;
for (key in this.members) {
for (i in this.members[key]) {
divisor = this.members[key][i];
if (!common[i] || common[i] < divisor) {
common[i] = divisor;
}
}
}
},
toLCM: function () { // 输出最小公倍数
var key, value, rst = 1;
for (key in this.common) {
value = this.common[key];
rst = rst * Math.pow(+key, value);
}
return rst;
}
};
new LCM(2, 3).toLCM(); // 6
new LCM(3, 4).toLCM(); // 12
new LCM(2, 3, 4).toLCM(); // 12
new LCM(3, 7, 9).toLCM(); // 63
new LCM(5, 8, 9).toLCM(); // 360
new LCM(10, 11, 15).toLCM(); // 330
new LCM(10, 11, 16).toLCM(); // 880
new LCM(10, 11, 17).toLCM(); // 1870
new LCM(3, 5, 7, 10, 11, 17, 18, 23).toLCM(); // 2709630
var lcm = function () {
var max = Math.max.apply(Math, arguments),
ret = max,
i = 0,
len = arguments.length
end = false;
while( !end ) {
end = true;
for(i = 0; i < len; i++) {
if( ret % arguments[i] !== 0 ) {
end = false;
ret = ret + max;
break;
}
}
}
return ret;
};
var lcm = function () {
var index = 1;
var bol = false;
while (1 == 1) {
bol = true;
for (var i = 0; i < arguments.length; i++) {
if (!/^[0-9]*[1-9][0-9]*$/.test(index / arguments[i])) {
bol = false;
}
}
if (bol == true) {
console.log(index);
break;
}
index++;
}
}
lcm(12,15); //60
编写一个函数,计算其参数的最小公倍数;每个参数都是一个非负整数。 不知道什么是公倍数? →_→ PS : 参数不限个数