Home > Backend Development > C++ > body text

C program to implement Euclidean algorithm

WBOY
Release: 2023-09-17 12:41:02
forward
1016 people have browsed it

C program to implement Euclidean algorithm

Problem

Implement Euclidean algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers and convert the results Output together with the given integer.

Solution

The solution to implement Euclidean algorithm to find the greatest common divisor (GCD) and least common multiple (LCM) of two integers is as follows-

Find GCD The logic with LCM is as follows -
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);
}
Copy after login

The function called is as follows-

int gcd_rec(int x, int y){
   if (y == 0)
      return x;
   return gcd_rec(y, x % y);
}
Copy after login

Program

The following is a C program for implementing the Euclidean algorithm to Find the greatest common divisor (GCD) and least common multiple (LCM) of two integers -< /p>

Live demonstration

#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&#39;s Procedure*/
   int gcd_rec(int x, int y){
   if (y == 0)
      return x;
   return gcd_rec(y, x % y);
}
Copy after login

Output

When the above program is executed, it will produces the following results -

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
Copy after login

The above is the detailed content of C program to implement Euclidean algorithm. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template