Finding the greatest common divisor of two numbers by using the tossing division and recursive thinking

Toss and divide

Euclid's algorithm, also known as toss and turns, is used to calculate the greatest common divisor of two non-negative integers a and b. There are two areas of application: mathematics and computer. The calculation formula gcd(a,b) => gcd(b,a mod b).


Introduction to Algorithm

Euclid's algorithm is an algorithm used to find the greatest common divisor of two positive integers. (It is called Euclidean algorithm because it was invented by Euclid)
Extension: Euclidean algorithm can be used in fields such as RSA encryption.

If you need the greatest common divisor of the two positive integers 1997 and 615, use Euclid's algorithm to proceed like this:
1997/615 = 3 (remaining 152)
615/152 = 4 (remaining 7)
152/7 = 21 (Remainder 5)
7/5 = 1 (Remainder 2)
5/2 = 2 (Remainder 1) 2/1
= 2 (Remainder 0) So
far, the greatest common divisor is 1.
Repeat the division operation with the divisor and the remainder, when the remainder is When it is 0, take the current divisor as the greatest common divisor, so the greatest common divisor 1 of 1997 and 615 is obtained.


Algorithm case

Case taken from PTA

Find the greatest common divisor

Use toss and turns division and recursion to find the greatest common divisor of two positive integers m and n.

Input format:
Input two positive integers m, n.

Output format:
output the dividing process and final results as required, separated by spaces between the output results.

Input sample:

21 35

Sample output:

gcd(21,35) gcd(35,21) gcd(21,14) gcd(14,7) 7

Author's code implementation

#include <iostream>
using namespace std;

int gcd(int a,int b){
    
    
	cout<<"gcd("<<a<<","<<b<<")"<<" ";
	if(a<b){
    
    
		int temp;
		temp=a;
		a=b;
		b=temp;
		cout<<"gcd("<<a<<","<<b<<")"<<" ";
	}
	
	int s=a%b;
	if(s==0){
    
    
	cout<<b;
	return b;
	}else{
    
    
	gcd(b,s);
	}
}

int main(){
    
    
	int a,b;
	cin>>a;
	cin>>b;
	gcd(a,b);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_38149225/article/details/109101717