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


問題

使用非遞迴函式查詢給定兩個數的最大公約數 (GCD)。

解決方案

下面解釋瞭如何使用非遞迴函式查詢給定兩個數的最大公約數 (GCD)。

演算法

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

步驟 1 − 開始

步驟 2 − 讀取整數 a 和 b

步驟 3 − 呼叫函式 G=GCD(a,b) (步驟 6)

步驟 4 − 列印 G 值

步驟 5 − 結束

步驟 6 − 被呼叫的函式:GCD(a,b)

a. Initialize the i=1, j, remainder
b. Remainder=i-(i/j*j)
c. Remainder=0 return j else goto step 4
d. GCD(G,remainder) return to main program

流程圖

下面是使用非遞迴函式查詢給定兩個數的最大公約數 (GCD) 的演算法流程圖。

示例

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

#include<stdio.h>
#include<conio.h>
#include<math.h>
int gcdnonR(int i,int j){
   int rem;
   rem=i-(i/j*j);
   if(rem==0)
      return j;
   else
      gcdnonR(j,rem);
}
void main(){
   int a,b;
   printf("enter the two numbers:");
   scanf("%d%d",&a,&b);
   printf("GCD of %d",gcdnonR(a,b));
   getch();
}

輸出

執行上述程式後,將產生以下結果:

enter the two numbers:10 30
GCD of 10

更新於:2021年8月31日

7K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.