JavaScript 查找两个数字的最大公约数(GCD)或最大公因数(HCF)的程序

JavaScript 查找两个数字的最大公约数(GCD)或最大公因数(HCF)的程序

在本文中,我们将学习如何在JavaScript中找到两个数字的最大公约数(GCD)或最大公因数(HCF)。最大公约数或最大公因数是两个数字中能够整除两者且没有余数的最大正整数。

GCD ( a, b ) = [ |a.b| ] / [ lcm(a, b) ]  
or,  
HCF of factors = Product of the Numbers/ LCM of numbers

示例:

Input: a = 20, b = 28  
Output: 4  
Explanation: The factors of 20 are 1, 2, 4, 5, 10 and 20.  
The factors of 28 are 1, 2, 4, 7, 14 and 28. Among these factors,   
1, 2 and 4 are the common factors of both 20 and 28.   
The greatest among the common factors is 4.

有几种方法可以用来计算两个数的最大公约数(HCF),如下所示:

  • 使用for循环
  • 使用递归方法

我们将通过示例来探讨上述所有方法及其基本实现。

使用for循环的JavaScript程序来找到两个数的最大公约数或最大公因数(GCD或HCF)

在这个方法中,我们使用循环来找到最大公约数(GCD/HCF),从1到两个数中的较小数进行迭代。当两个数都可以整除时,更新最大公约数。

语法:

for ( variable of iterableObjectName) {  
    . . .  
}

例子:

Javascript

function myFunction(a, b) { 
    let smaller = Math.min(a, b); 
    let hcf = 1; 
  
    for (let i = 1; i <= smaller; i++) { 
        if (a % i === 0 && b % i === 0) { 
            hcf = i; 
        } 
    } 
  
    return hcf; 
} 
  
const num1 = 20; 
const num2 = 12; 
  
console.log("GCD of the giving numbers(20,12) is:",  
    myFunction(num1, num2));

输出

GCD of the giving numbers(20,12) is: 4

使用递归方法查找两个数的最大公约数或最小公倍数的JavaScript程序

在这种方法中,递归函数myFunction使用欧几里德算法计算最大公约数。如果b=0,则返回a;否则,以b和a/b的余数递归调用。

语法

function myFunction(a, b) {  
    if ( b === 0 ) {  
        return a;  
    }  
    return myFunction(b, a % b);  
}

示例: 在这个示例中,我们使用了上面解释的方法。

JavaScript

function myFunction(a, b) { 
    if (b === 0) { 
        return a; 
    } 
    return myFunction(b, a % b); 
} 
  
let num1 = 12; 
let num2 = 18; 
let result = myFunction(num1, num2); 
console.log(`GCD of {num1} and{num2} is ${result}`);

输出

GCD of 12 and 18 is 6

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程