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

更新於: 2021年9月1日

1千+瀏覽

開啟你的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.