JS如何求最大公约数 [英] JS how to find the greatest common divisor

查看:38
本文介绍了JS如何求最大公约数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JavaScript 找到最大公约数.

I would like to find the greatest common divisor using JavaScript.

有谁做过并愿意分享吗?

Anyone done that before and willing to share?

推荐答案

这是一个递归解决方案,使用欧几里得算法.

Here is a recursive solution, using the Euclidean algorithm.

 var gcd = function(a, b) {
  if (!b) {
    return a;
  }

  return gcd(b, a % b);
}

我们的基本情况是 b 等于 0.在这种情况下,我们返回 a.

Our base case is when b is equal to 0. In this case, we return a.

当我们递归时,我们交换输入参数,但我们将 a/b 的剩余部分作为第二个参数传递.

When we're recursing, we swap the input arguments but we pass the remainder of a / b as the second argument.

这篇关于JS如何求最大公约数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆