使用遞迴函式查詢數字的最大公約數的C程式


問題

使用C程式語言中的遞迴函式,找到給定兩個數字的最大公約數(GCD)。

解決方案

使用遞迴函式找到給定兩個數字的最大公約數(GCD)的解決方案如下:

演算法

請參考下面給出的演算法,使用遞迴函式找到給定兩個數字的最大公約數(GCD)。

步驟1 - 定義遞迴函式。

步驟2 - 讀取兩個整數a和b。

步驟3 - 呼叫遞迴函式。

a. if i>j
b. then return the function with parameters i,j
c. if i==0
d. then return j
e. else return the function with parameters i,j%i.

流程圖

下面給出了一個流程圖,用於使用遞迴函式找到給定兩個數字的最大公約數(GCD)的演算法。

示例

以下是使用遞迴函式查詢給定兩個數字的最大公約數(GCD)的C程式

 線上演示

#include<stdio.h>
#include<math.h>
unsigned int GCD(unsigned i, unsigned j);
int main(){
   int a,b;
   printf("Enter the two integers: 
");    scanf("%d%d",&a,&b);    printf("GCD of %d and %d is %d
",a,b,GCD(a,b));    return 0; } /* Recursive Function*/ unsigned int GCD(unsigned i, unsigned j){    if(j>i)       return GCD(j,i);    if(j==0)       return i;    else       return GCD(j,i%j); }

輸出

執行上述程式時,會產生以下結果:

Enter the two integers: 4 8
GCD of 4 and 8 is 4

更新於: 2021年8月31日

24K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.