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

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

问题描述

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

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

之前是否有人愿意分享?

Anyone done that before and willing to share?

推荐答案

这里是递归解决方案。

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天全站免登陆