如何求一组数字上的GCD、LCM
计算一组数字的最大公约数和最小公倍数的最简单方法是什么?可以使用哪些数学函数来查找此信息?
What would be the easiest way to calculate Greatest Common Divisor and Least Common Multiple on a set of numbers? What math functions can be used to find this information?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
我使用欧几里德算法来找到两个数字的最大公约数;可以迭代它以获得更大的数字集的 GCD。
最小公倍数有点棘手,但最好的方法可能是通过 GCD 减少,可以类似地迭代:
I've used Euclid's algorithm to find the greatest common divisor of two numbers; it can be iterated to obtain the GCD of a larger set of numbers.
Least common multiple is a little trickier, but probably the best approach is reduction by the GCD, which can be similarly iterated:
GCD 有一个欧几里得算法,
顺便说一下,
a
和b
应大于或等于0
,并且 LCM< /a> = <代码>|ab| /GCF(a, b)There is an Euclid's algorithm for GCD,
By the way,
a
andb
should be greater or equal0
, and LCM =|ab| / GCF(a, b)
它没有内置功能。您可以使用欧几里德算法找到两个数字的最大公约数。
对于一组数字,
递归地应用它。
LCM 也一样:
There are no build in function for it. You can find the GCD of two numbers using Euclid's algorithm.
For a set of number
Apply it recursively.
Same for LCM:
如果您可以使用 Java 8(并且实际上想要),您可以使用 lambda 表达式从功能上解决此问题:
我以 Jeffrey Hantin 的答案< /a>,但
numbers
的 gcd - 数组转换为函数式语法,它更紧凑,并且在我看来更容易阅读(至少如果您习惯函数式编程),由于额外的函数调用,这种方法可能会稍微慢一些,但这对于大多数人来说可能根本不重要用例。
If you can use Java 8 (and actually want to) you can use lambda expressions to solve this functionally:
I oriented myself on Jeffrey Hantin's answer, but
numbers
-Array into functional syntax, which is more compact and IMO easier to read (at least if you are used to functional programming)This approach is probably slightly slower due to additional function calls, but that probably won't matter at all for the most use cases.
在 Java 8 中,有更优雅、更实用的方法来解决这个问题。
LCM:
GCD:
当然,如果一个参数为0,则两种方法都不起作用。
With Java 8, there are more elegant and functional ways to solve this.
LCM:
GCD:
Of course if one argument is 0, both methods will not work.
对于
gcd
你 cad 执行如下操作:for
gcd
you cad do as below:导入java.util.Scanner;
公共类 Lcmhcf {
import java.util.Scanner;
public class Lcmhcf {
在这里,第一个 for 循环是获取从“2”开始的每个数字。然后 if 语句检查 number(i) 是否整除 lcm,如果是,则跳过该否。如果没有,那么下一个 for 循环就是寻找否。它可以除以数字(i),如果发生这种情况,我们不需要那个。我们只想要它的额外因素。因此,如果该标志为真,则意味着已经存在一些“否”因素。 lcm 中的“i”。所以我们将这些因子相除,然后将额外的因子乘以 lcm。如果该数字不能被之前的任何数字整除。然后只需将其乘以 lcm 即可。
here, first for loop is for getting every numbers starting from '2'. then if statement check whether the number(i) divides lcm if it does then it skip that no. and if it doesn't then next for loop is for finding a no. which can divides the number(i) if this happens we don't need that no. we only wants its extra factor. so here if the flag is true this means there already had some factors of no. 'i' in lcm. so we divide that factors and multiply the extra factor to lcm. If the number isn't divisible by any of its previous no. then when simply multiply it to the lcm.