-->
当前位置:首页 > 题库

PROGRAMMING:Finding the greatest common divisor by recursion

Luz5年前 (2021-05-10)题库457
The greatest common divisor (GCD) of two positive integers is the largest integer that can divide the two integers. Please implement the program, using recursive method to calculate the greatest common divisor of two numbers.
#####* * recursive method:**
*When 'a > b', the greatest common divisor of 'a' and 'B' is the same as that of 'a - B' and 'B', that is, 'GCD (a, b) = GCD (a-b.b)`
*When 'b > a', the greatest common divisor of 'a' and 'B' is the same as that of 'a' and 'a - B', that is, 'GCD (a, b) = GCD (a.b-a)`
*When a = B, the greatest common divisor of a and B is a (or b)
*
###Input format:
The user enters two positive integers from the keyboard.
###Output format:
Outputs the greatest common divisor of two positive integers.
If the input number is not a positive integer, the program outputs:
```
Input Data error!
```
###Function interface definition:
```
int Gcd(int a, int b);
```
Where 'a' and 'B' are two positive integers entered by the user.
Function returns the greatest common divisor of 'a' and 'B'.
If 'a' or 'B' is not a positive integer, the function returns' - 1 '.
###Main program example:
Here is the main function and an example of calling GCD function
```
#include
int Gcd(int a, int b);
int main()
{
int a, b, c;
scanf("%d %d", &a, &b);
c = Gcd(a,b);
if (c != - 1)
{
printf("%d\n", c);
}
else
{
printf("Input Data error!\ n");
}
return 0;
}
/*Please complete the GCD function here*/
```
###Input example:
Here is a set of inputs. For example:
```in
15 20
```
###Output example:
The corresponding output is given here. For example:
```out
five
```







answer:If there is no answer, please comment