Today I check on the Internet "JS to findan array of elements of the least common multiple ", whether it is Google or Baidu, the answer is found to be the same, the most critical is that it is wrong.
Where's the mistake? Just look at the feeling is correct, and you enter a few different arrays, the output is correct, but, when I input [2,3,4] unexpectedly is 24, this is obviously wrong, and the input [0,1] when the output is 1,
I found these two points wrong. All right, post my own code.
var LCM = function () {
Todo:program Me
var m=0;
for (Var i=0;i<arguments.length;i++)
{
if (arguments[i]==0)
return 0;
M=GCD (M,arguments[i]);
}
return m;
};
function gcd (A, b) {
var Maxnum=math.max (A, B), Minnum=math.min (A, b), Count;
if (a===0| | b===0)
return maxnum;
for (Var i=1;i<=maxnum;i++)
{
Count=minnum*i;
if (count%maxnum===0)
{
return count;
Break
}
}
}
The passed-in array parameter is a nonnegative integer.
If that's not enough, here's the code for Daniel:
var LCM = function () {
function gcd (A, b) {
if (a = = 0) return b;
Return gcd (B%a, a);
}
return Array.prototype.slice.apply (arguments). reduce (function (A, b) {return A*B/GCD (A, b);}, 1);
};
is not super concise.
If you don't think it's enough:
var LCM = function ()
{
var numbers = Array.prototype.slice.call (arguments);
if (!numbers.length)
return null;
if (! Math.min.apply (null, numbers))
return 0;
Return Numbers.reduce (Lcmof2numbers, Numbers.pop ());
};
var lcmof2numbers = function (Number1, number2)
{
Return number1 * number2/gcdof2numbers (Number1, number2);
};
var gcdof2numbers = function (Number1, number2)
{
Return!number2? Number1:gcdof2numbers (number2, number1% number2);
};
So is it possible to do this:
var LCM = function () {
if (!arguments.length) return false;
if (arguments.length = = 1) return arguments[0];
var length = Arguments.length,
base = Arguments[0];
for (var i=1; i < length; i++) {
var current = Arguments[i],
Bbase = base;
while (base && current) {
if (Base > Current) {
Base = base% Current;
} else {
Current = current% base;
}
}
Base = (Bbase * arguments[i])/(base+current);
}
return base;
};
JS to find the least common multiple of an array element