实现 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 中考祝福语 简短50字