首頁  >  文章  >  後端開發  >  C程式實作歐幾裡得演算法

C程式實作歐幾裡得演算法

WBOY
WBOY轉載
2023-09-17 12:41:02963瀏覽

C程式實作歐幾裡得演算法

問題

實作歐幾裡得演算法來找出兩個整數的最大公約數(GCD) 和最小公倍數(LCM),並將結果與給定整數一起輸出。

實作歐幾裡得演算法求兩個整數的最大公約數(GCD) 與最小公倍數(LCM) 的解如下-

求GCD和LCM 的邏輯如下-
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);
}

調用的函數如下-

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

程序

以下是C 程序,用於實現歐幾里德演算法,以求兩個整數的最大公約數(GCD) 和最小公倍數(LCM) -

 現場示範

#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);
}

輸出

當上述程序執行時,會產生以下結果-

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

以上是C程式實作歐幾裡得演算法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除