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); }
程序
以下是为了**实现欧几里得算法来寻找两个整数的最大公约数(GCD)和最小公倍数(LCM)**的C语言程序——
#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("
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
广告