C程序实现欧几里得算法

2023年 9月 17日 16.9k 0

C程序实现欧几里得算法

问题

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

解决方案

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

求 GCD 和 LCM 的逻辑如下 -

if(firstno*secondno!=0){
   gcd=gcd_rec(firstno,secondno);
   printf("

The GCD of %d and %d is %d

",firstno,secondno,gcd);
   printf("

The LCM of %d and %d is %d

",firstno,secondno,(firstno*secondno)/gcd);
}

登录后复制

调用的函数如下 -

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

登录后复制

程序

以下是 C 程序,用于实现欧几里得算法,以求两个整数的最大公约数 (GCD) 和最小公倍数 (LCM) -

 现场演示

#include
int gcd_rec(int,int);
void main(){
   int firstno,secondno,gcd;
   printf("Enter the two no.s to find GCD and LCM:");
   scanf("%d%d",&firstno,&secondno);
   if(firstno*secondno!=0){
      gcd=gcd_rec(firstno,secondno);
      printf("

The GCD of %d and %d is %d

",firstno,secondno,gcd);
      printf("

The LCM of %d and %d is %d

",firstno,secondno,(firstno*secondno)/gcd);
   }
   else
      printf("One of the entered no. is zero:Quitting

");
   }
   /*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 two no.s to find GCD and LCM:4 8

The GCD of 4 and 8 is 4

The LCM of 4 and 8 is 8

登录后复制

以上就是C程序实现欧几里得算法的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论