PTA 6-5 C Programming Exercises 7.7.2 Finding the greatest common divisor by dividing into phases (4 points)

6-5 C Programming Exercises 7.7.2 Finding the greatest common divisor through division (4 points)

topic

The Greatest Common Divisor (GCD) of two positive integers is the largest integer that can divide these two integers evenly. Please implement a function to calculate the greatest common divisor of two numbers using Euclid's algorithm (also called division by tossing and turning).

Euclid's algorithm: the greatest common divisor of two integers is equal to the greatest common divisor of the smaller number and the remainder of the division of the two numbers.

For example, find the greatest common divisor of 252 and 105:

Because 252% 105 = 147, the greatest common divisor of 252 and 105 is also the greatest common divisor of 147 and 105.

Because 147% 105 = 42, the greatest common divisor of 252 and 105, that is, the greatest common divisor of 147 and 105, that is, the greatest common divisor of 105 and 42, and so on, we can finally get 21. In this process, the larger number is reduced, so continue to perform the same calculation to continuously reduce the two numbers until one of them becomes zero. At this time, the remaining number that has not become zero is the greatest common divisor of the two numbers.

Function interface definition:

int Gcd(int a, int b);

Among them, a and b are two positive integers entered by the user.

The function returns the greatest common divisor of a and b.

If a or b is less than or equal to 0, the function returns -1.

Sample referee test procedure:

在这里给出函数被调用进行测试的例子:
#include <stdio.h>
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 number should be positive!\n");
    }
    return 0;
}

/* 请在这里填写答案 */

Input sample:

Here is a set of inputs. E.g:

15 20

Sample output:

The corresponding output is given here. E.g:

5

Source code:

int Gcd(int a, int b)
{
    
    
	int t;
		if(a<=0||b<=0){
    
    
		return -1;
 }
	if(a<b){
    
    
		t=b;
		b=a;
		a=t;
	}
	while(b!=0)
	{
    
    
		a=a%b;
		if(a<b){
    
    
		t=b;
		b=a;
		a=t;
	}	
	}
	return a;
}

Guess you like

Origin blog.csdn.net/Anemia_/article/details/111684999