c/c++ find the greatest common divisor of two numbers (recursive version)

**

c/c++ find the greatest common divisor of two numbers (recursive version)

**
We first assume that x>y gcd(x,y) is the greatest common divisor of x and y, first assume that gcd(x,y)=d, d is the greatest common divisor of x and y, then we can get such a conclusion : X can be divisible by d, and y can be divisible by d. OK, pay attention, we need to transform, because x and y can be divisible by d, so xy can also be divisible by d (we assumed that x>y in advance), and then change it, because xy can be divisible by d, So (x%y) can also be divisible by d. OK, we can get gcd(x,y)=gcd(xy,y)=gcd(x%y,y), it should be understandable (you think about it, y has not changed, x,xy,x%y are all Can be divisible by d, so the final answer is definitely d) good, we can write code happily after we know this idea (recursive version)

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int f(int x, int y) {
    
    
	if (x%y==0) {
    
    
		return y;
	}
	return f(y, x%y);//这里不懂的可以思考下额  也比较简单
}
int main() {
    
    
	int x, y;
	cin>>x>>y;//输入x与y
	if (x < y)
		swap(x, y);//如果x<y就交换x与y的值
	int ans = f(x, y);
	printf("%d", ans);
	return 0;
}

Thank you for reading, and the author's level is limited. It is inevitable that there are errors. If readers find errors, please criticize them and leave a message in the message area. I will definitely modify them as soon as possible. Thank you.

Guess you like

Origin blog.csdn.net/m0_46833224/article/details/113796262