最大公約數


根據最大公約數的如下3條性質,采用遞歸法編寫計算最大公約數的函數Gcd(),在主
函數中調用該函數計算並輸出從鍵盤任意輸入的兩正整數的最大公約數。
性質1 如果a>b,則a和b與a-b和b的最大公約數相同,即Gcd(a, b) = Gcd(a-b, b)
性質2 如果b>a,則a和b與a和b-a的最大公約數相同,即Gcd(a, b) = Gcd(a, b-a)
性質3 如果a=b,則a和b的最大公約數與a值和b值相同,即Gcd(a, b) = a = b
要求如下:
(1)從鍵盤任意輸入的兩整數
主函數調用Gcd()函數,並輸出兩整數的最大公約數。
(2)Gcd函數原型為:
int Gcd(int a, int b);
如果輸入的數不是正整數,則返回-1,否則,返回兩個數的最大公約數。
(3)**輸入提示信息格式要求:"Input a,b:"
輸入兩個整數時用,號分隔
**輸出提示信息要求:
若輸入不是正整數,則輸出"Input number should be positive!\n"
否則輸出"Greatest Common Divisor of %d and %d is %d\n"

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 int Gcd(int a, int b);
 5 
 6 int Gcd(int a, int b)
 7 {
 8     if(a<=0||b<=0)
 9         return -1;
10     else if(a>b)
11         return Gcd(a-b, b);
12     else if(a<b)
13         return Gcd(a, b-a);
14     else
15         return a;
16 }
17 
18 int main()
19 {
20     int a,b,res;
21     printf("Input a,b:");
22     scanf("%d,%d",&a,&b);
23     res=Gcd(a,b);
24     if(res==-1)
25         printf("Input number should be positive!\n");
26     else
27         printf("Greatest Common Divisor of %d and %d is %d\n",a,b,res);
28     return 0;
29 }

 


免責聲明!

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



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