实现 Euclid 算法的 C 程序

问题

实现欧几里得算法以找到两个整数的最大公约数 (GCD) 和最小公倍数 (LCM),并将结果与给定的整数一起输出。

解决方案

实现欧几里德算法以找到两个整数的最大公约数(GCD)和最小公倍数(LCM)的解决方案如下 -

用于查找 GCD 和 LCM 的逻辑如下 -

if(firstno*secondno!=0){
   gcd=gcd_rec(firstno,secondno);
   printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);
   printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,(firstno*secondno)/gcd);
}

被调用的函数如下 -

int gcd_rec(int x, int y){
   if (y == 0)
      return x;
   return gcd_rec(y, x % y);
}

程序

以下是实现欧几里德算法以找到两个整数的最大公约数 (GCD) 和最小公倍数 (LCM)的 C 程序-

#include<stdio.h>
int gcd_rec(int,int);
void main(){
   int firstno,secondno,gcd;
   printf("Enter the twono.sto find GCD and LCM:");
   scanf("%d%d",&firstno,&secondno);
   if(firstno*secondno!=0){
      gcd=gcd_rec(firstno,secondno);
      printf("\nThe GCD of %d and %d is %d\n",firstno,secondno,gcd);
      printf("\nThe LCM of %d and %d is %d\n",firstno,secondno,(firstno*secondno)/gcd);
   }
   else
      printf("One of the entered no. is zero:Quitting\n");
   }
   /*Function for Euclid's Procedure*/
   int gcd_rec(int x, int y){
   if (y == 0)
      return x;
   return gcd_rec(y, x % y);
}
输出结果

执行上述程序时,会产生以下结果 -

Enter the twono.sto find GCD and LCM:4 8

The GCD of 4 and 8 is 4

The LCM of 4 and 8 is 8