实现 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输出结果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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短