如何找到一组数字的最小公倍数?

编程入门 行业动态 更新时间:2024-10-09 11:19:59
本文介绍了如何找到一组数字的最小公倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给定一个包含两个数字的数组,让它们定义一系列数字的开始和结束.例如,[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

更多推荐

如何找到一组数字的最小公倍数?

本文发布于:2023-11-29 10:02:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646085.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最小公倍数   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!