使用欧几里德算法的最小公倍数值

编程入门 行业动态 更新时间:2024-10-09 05:12:35
本文介绍了使用欧几里德算法的最小公倍数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用欧几里得算法计算值数组的最小公倍数

I want to calculate the least common multiple of an array of values, using Euclideans algorithm

我正在使用这个伪代码实现:在维基百科

I am using this pseudocode implementation: found on wikipedia

function gcd(a, b) while b ≠ 0 t := b; b := a mod b; a := t; return a;

我的javascript实现是这样的

My javascript implementation is such

function smallestCommons(arr) { var gcm = arr.reduce(function(a,b){ let minNum = Math.min(a,b); let maxNum = Math.max(a,b); var placeHolder = 0; while(minNum!==0){ placeHolder = maxNum; maxNum = minNum; minNum = placeHolder%minNum; } return (a*b)/(minNum); },1); return gcm; } smallestCommons([1,2,3,4,5]);

我收到错误,在我的whileloop上

I get error, on my whileloop

无限循环

Infinite loop

编辑在结束时进行了一些更正gcm函数,我用0作为初始起始值,它应该是1,因为你不能从0开始有一个gcm。

EDIT Some corrections were made, at the end of gcm function, I used 0 as the initial start value, it should be 1, since you can't have a gcm from 0.

EDIT2 预期的输出应该是60,因为那是1,2,3,4,5的最小公倍数

EDIT2 The expected output should be 60, since thats the least common multiple of 1,2,3,4,5

推荐答案

你故意纠缠所有变量和操作符序列? ; - )

Did you intentionally tangle all variables and operator sequence? ;-)

while(minNum!==0){ placeHolder = minNum; minNum = maxNum % minNum; maxNum = placeHolder; } //here maxNum = GCD(a,b) return (a*b) / (maxNum); //LCM

更多推荐

使用欧几里德算法的最小公倍数值

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

发布评论

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

>www.elefans.com

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