首页 > 后端开发 > C++ > 正文

C程序实现欧几里得算法

WBOY
发布: 2023-09-17 12:41:02
转载
1317人浏览过

c程序实现欧几里得算法

问题

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

解决方案

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

求 GCD 和 LCM 的逻辑如下 -
if(firstno*secondno!=0){
   gcd=gcd_rec(firstno,secondno);
   printf("</p><p>The GCD of %d and %d is %d</p><p>",firstno,secondno,gcd);
   printf("</p><p>The LCM of %d and %d is %d</p><p>",firstno,secondno,(firstno*secondno)/gcd);
}
登录后复制

调用的函数如下 -

算家云
算家云

高效、便捷的人工智能算力服务平台

算家云 37
查看详情 算家云
int gcd_rec(int x, int y){
   if (y == 0)
      return x;
   return gcd_rec(y, x % y);
}
登录后复制

程序

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

 现场演示

#include<stdio.h>
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("</p><p>The GCD of %d and %d is %d</p><p>",firstno,secondno,gcd);
      printf("</p><p>The LCM of %d and %d is %d</p><p>",firstno,secondno,(firstno*secondno)/gcd);
   }
   else
      printf("One of the entered no. is zero:Quitting</p><p>");
   }
   /*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程序实现欧几里得算法的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号