문제
Euclid의 알고리즘을 구현하여 두 정수의 최대공약수(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<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("\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 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