两个数字的HCF(最高公因数)或GCD(最大公因数)是将两者相除的最大数。
例如20和28的GCD为4,98和56的GCD为14。
我们在下面的文章中讨论了递归解决方案。递归程序可以找到两个数字的GCD或HCF
下面是Euclid算法的迭代实现
C++
// C++ program to find HCF of two
// numbers iteratively.
#include
using namespace std;
int hcf(int a, int b)
{
while (a != b)
{
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
// Driver code
int main()
{
int a = 60, b = 96;
cout << hcf(a, b) << endl;
return 0;
}
// This code is contributed by shubhamsingh10
C
// C program to find HCF of two
// numbers iteratively.
#include
int hcf(int a, int b)
{
while (a != b) {
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
int main()
{
int a = 60, b = 96;
printf("%d\n", hcf(a, b));
return 0;
}
Java
// JAVA Code for Program to find
// HCF iteratively
import java.util.*;
class GFG {
static int hcf(int a, int b)
{
while (a != b)
{
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
/* Driver program */
public static void main(String[] args)
{
int a=60, b=96;
System.out.println(hcf(a, b));
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
// Python program to find HCF of two
// numbers iteratively.
def hcf(a, b):
while (a != b):
if (a > b):
a = a - b
else:
b = b - a
return a
a = 60
b = 96
print(hcf(a, b))
C#
// C# Code for Program to find
// HCF iteratively
using System;
class GFG {
static int hcf(int a, int b)
{
while (a != b)
{
if (a > b)
a = a - b;
else
b = b - a;
}
return a;
}
// Driver program
public static void Main()
{
int a = 60, b = 96;
Console.WriteLine(hcf(a, b));
}
}
// This code is contributed by vt_m.
PHP
$b)
$a = $a - $b;
else
$b = $b - $a;
}
return $a;
}
// Driver code
$a = 60; $b = 96;
echo hcf($a, $b), "\n";
// This code is contributed by ajit
?>
Javascript
输出:
12