本關任務:設計函數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 }