C語言 遞歸求解最大公約數


本關任務:設計函數RecurMaxCommonFactor(),實現遞歸求解兩個正整數的最大公約數。

最大公約數可用如下三個性質實現: 性質1 如果a>b,則a和b的最大公約數與a-b和b的最大公約數相同; 性質2 如果a<b,則a和b的最大公約數與a和b-a的最大公約數形同; 性質3 如果a=b,則a和b的最大公約數與a值或b值相同。

編程要求

根據提示,在右側編輯器補充遞歸函數RecurMaxCommonFactor(),在main函數中輸入兩個正整數,調用所寫的函數計算出最大公約數並輸出。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int MaxCommonFactor(int a, int b);
 4 
 5 int main()
 6 {
 7     /****************Begin*************/
 8     int a,b;
 9     printf("Input two positive integers,a,b:\n");
10     scanf("%d,%d",&a,&b);
11   if(a<0 ||b<0){
12     printf("Input error!");
13   }else{
14    printf("MaxCommonFactor = %d",MaxCommonFactor(a,b));
15   }
16    
17     return 0;
18     /****************End***************/
19 
20 }
21 
22 //º¯Êý¹¦ÄÜ£º ¼ÆËãÁ½¸öÕýÕûÊýµÄ×î´ó¹«Ô¼Êý£¬-1±íʾûÓÐ×î´ó¹«Ô¼Êý
23 //ÒªÇóʹÓõݹéʵÏÖ
24 int MaxCommonFactor(int a, int b)
25 {
26     /****************Begin*************/
27 if(a>b)
28         return MaxCommonFactor(a-b,b);
29     else if(a<b)
30         return MaxCommonFactor(b-a,a);
31     else if(a==b)
32         return a;
33     /****************End***************/
34 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM