本文介绍了如何找到一组数字的最小公倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个包含两个数字的数组,让它们定义一系列数字的开始和结束.例如,[2,6]
表示范围 2,3,4,5,6.我想编写 javascript 代码来找到该范围的最小公倍数.我下面的代码仅适用于小范围,而不适用于 [1,13]
(即范围 1,2,3,4,5,6,7,8,9,10,11,12,13),这会导致堆栈溢出.如何有效地找到范围的最小公倍数?
Given an array of two numbers, let them define the start and end of a range of numbers. For example, [2,6]
means the range 2,3,4,5,6. I want to write javascript code to find the least common multiple for the range. My code below works for small ranges only, not something like [1,13]
(which is the range 1,2,3,4,5,6,7,8,9,10,11,12,13), which causes a stack overflow. How can I efficiently find the least common multiple of a range?
function leastCommonMultiple(arr) {
var minn, max;
if ( arr[0] > arr[1] ) {
minn = arr[1];
max = arr[0];
} else {
minn = arr[0];
max = arr[1];
}
function repeatRecurse(min, max, scm) {
if ( scm % min === 0 && min < max ) {
return repeatRecurse(min+1, max, scm);
} else if ( scm % min !== 0 && min < max ) {
return repeatRecurse(minn, max, scm+max);
}
return scm;
}
return repeatRecurse(minn, max, max);
}
推荐答案
我认为这可以完成工作.
I think this gets the job done.
function leastCommonMultiple(min, max) {
function range(min, max) {
var arr = [];
for (var i = min; i <= max; i++) {
arr.push(i);
}
return arr;
}
function gcd(a, b) {
return !b ? a : gcd(b, a % b);
}
function lcm(a, b) {
return (a * b) / gcd(a, b);
}
var multiple = min;
range(min, max).forEach(function(n) {
multiple = lcm(multiple, n);
});
return multiple;
}
leastCommonMultiple(1, 13); // => 360360
这篇关于如何找到一组数字的最小公倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!