使用欧几里得算法求最大公约数 (GCD/HCF) 和最小公倍数 (LCM) 的 C 语言程序


2022 年 5 月 10 日, Learn eTutorial
2249

GCD 或 HCF 是两个数的最大公约数,LCM 是两个数的最小公倍数。 为了更好地理解这个求最大公约数 (GCD/HCF) 和最小公倍数 (LCM) 的 C 程序示例,我们始终建议您学习以下列出的 C 语言编程 的基本主题:

什么是 GCD 或 HCF?

GCD 或 HCF 是指能同时整除两个数的最大数。假设我们有两个数 3660,那么它们的最大公约数 (GCD/HCF) 是 12。因为

C 语言程序中如何计算 GCD 或 HCF?

为了使用 C 语言程序求 GCD 或 LCM,我们使用 欧几里得算法 和给定输入的 LCM。

欧几里得算法指出,如果较大的数被其与较小数的差替换,两个数的最大公约数不会改变。 在这个 C 语言程序中,我们首先检查哪个是最大的数并将其指定为被除数,另一个指定为除数,然后在一个 `while` 循环中使用 **模** 运算符来找到 **GCD** 或 **HCF**。

什么是 LCM?C 语言程序中如何计算 LCM?

LCM 是两个数的最小公倍数。它是能被两个数同时整除的最小正整数。

假设我们有两个数 46,为了求它们的 LCM,我们必须找到它们的倍数,其中最小公倍数是 12。在找到 GCDHCF 之后,对于 LCM,我们有一个明确的公式。

"LCM = num1 * num2 / GCD"。

假设我们取两个数,比如“a”和“b”。我们再取一个数“d”,使得“a/d”和“b/d”没有余数,或者余数为零,这类数称为公约数。公约数“s”不能太大,因为约数不能大于被除数。所以必须满足“d <= a”和“d <= b”的条件。

算法

步骤 1: 将头文件导入 C 语言程序以使用内置函数。

步骤 2: 使用 void 开始主程序执行,表示不返回任何内容。

步骤 3: 初始化变量,例如余数LCMGCD被除数除数等。

步骤 4: 使用 printfscanf 语句从用户那里接受两个数字。

步骤 5: 使用 if 语句检查 num1 是否大于 num2

步骤 6: 如果是,将 num1 赋值为被除数,num2 赋值为除数。

步骤 7: 如果 num2 较大,则使用 else 进行相反的赋值。

步骤 8: 使用 MOD 运算符计算 num1num2 之间的余数。

步骤 9: 使用 while 循环直到余数不等于零。

步骤 10: 将被除数替换为除数,将除数替换为余数。

步骤 11: 将除数赋值给 GCD

步骤 12: 使用公式 num1 * num2 / GCD 计算 LCM

步骤 13: 打印 GCDLCM 的结果。

C 语言源代码

                                          #include <stdio.h>

void main()
{
  int num1, num2, GCD, LCM, remainder, numerator, denominator;         /* declares the variables gcd, lcm, remainder etc as integers  */
  printf("Enter two numbers\n");
  scanf("%d %d", & num1, & num2);                  /*  accepts two numbers from the user  */
  if (num1 > num2)
  {
     numerator = num1;
     denominator = num2;
  } 
  else 
  {
                                                          /* checks and assigns the value for numerator and denominator  */
    numerator = num2;
    denominator = num1;
  }
  remainder = num1 % num2;           /* use mod operator to find the remainder  */
  while (remainder != 0) 
  {
    numerator = denominator;           /* using Euclid's algorithm to interchange the values of variables  */
    denominator = remainder;
    remainder = numerator % denominator;
  }
    GCD = denominator;
    LCM = num1 * num2 / GCD;
    printf("GCD of %d and %d = %d \n", num1, num2, GCD);         /* after gcd we find out the value of lcm */
    printf("LCM of %d and %d = %d \n", num1, num2, LCM);
} /* End of main() */
                                      

输出

RUN 1

Enter two numbers
5
15

GCD of 5 and 15 = 5
LCM of 5 and 15 = 15