Skip to content

Latest commit

 

History

History
54 lines (37 loc) · 1.28 KB

File metadata and controls

54 lines (37 loc) · 1.28 KB

C++ 程序:使用递归查找 GCD

原文: https://www.programiz.com/cpp-programming/examples/hcf-recursion

在 C 编程中使用递归查找两个正整数(由用户输入)的 GCD 的示例。

要理解此示例,您应该了解以下 C++ 编程主题:


该程序从用户获取两个正整数,并使用递归计算 GCD。

访问此页面以了解如何使用循环来计算 GCD

示例:使用递归计算 HCF

#include <iostream>
using namespace std;

int hcf(int n1, int n2);

int main()
{
   int n1, n2;

   cout << "Enter two positive integers: ";
   cin >> n1 >> n2;

   cout << "HCF of " << n1 << " & " <<  n2 << " is: " << hcf(n1, n2);

   return 0;
}

int hcf(int n1, int n2)
{
    if (n2 != 0)
       return hcf(n2, n1 % n2);
    else 
       return n1;
} 

输出

Enter two positive integers: 366 60
HCF of 366 and 60 is: 6