最大公约数

根据最大公约数的如下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! "
否则输出"Greatest Common Divisor of %d and %d is %d "

 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!
");
26     else
27         printf("Greatest Common Divisor of %d and %d is %d
",a,b,res);
28     return 0;
29 }
原文地址:https://www.cnblogs.com/crane-practice/p/3727852.html