函數與遞歸練習

Description:
請實現下面兩個函數,分別完成對兩個數求最大公約數,和求一個數階乘的求解。

要求:兩個函數都需要遞歸實現求解,否則本題按0分處理。主函數已給出如下:

#include<stdio.h>

// function declares here, first is Greatest common divisor, next is factorial.
int gcd(int m, int n);
int fac(int p);

int main(void) {
  int a, b, c;
  scanf("%d%d%d", &a, &b, &c);
  printf("%d %d\n", gcd(a, b), fac(c));
}

// next is function's defintion.

你只需要利用遞歸實現這兩個函數。

ps: 強烈建議大家課後可以看看期中測試題目的Maxmal Discount那道題的答案。(學習遞歸函數的運用,合併排序,指針,內存管理)

 因爲所寫的內容比較少,避免誤判爲抄襲,請各位爲你的函數多寫註釋。

Hint:
最大公約數:輾轉相除法。

階乘:按定義求解即可。

#include<stdio.h>
// function declares here, first is Greatest common divisor, next is factorial.
int gcd(int m, int n) {
    if (n % m == 0)
        return(m);
    else
        return (gcd(n%m, m));
}
int fac(int p) {
    if (p == 0 || p == 1)
        return(1);
        //0或者1就返回1
    else
        return(p * fac(p - 1));
        //p*已知p-1的階乘
}
int main() {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);
    printf("%d %d\n", gcd(a, b), fac(c));
    return 0;
}
// next is function's defintion.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章