gcd and lcm (greatest common divisor, least common multiple)

GCD (greatest common divisor) is the greatest common divisor, and lcm (least common multiple) is the least common multiple.
**

gcd algorithm

**
The gcd algorithm uses the Euclidean algorithm, that is, the rolling and dividing method. The specific principle is:
1. There are two numbers a and b. We pass the larger number to maxn and the smaller number to maxn. minx
2. Use maxn to perform the remainder operation on minx. If the remainder is 0, then the greatest common divisor of a and b is a. 3. If the
remainder is not 0, the greatest common divisor of a and b is the greatest common divisor of minx and the remainder number, we calculate in the first step of the cycle
Code display

int gcd (int a,int b) {
    
     //b为较大的那个数,即maxn
	while(b%a != 0&&a) {
    
    
		int ans  = b%a;
		b = a;
		a = ans;
	}
	return a ;
}

**

lcm algorithm

**
To find the least common multiple of two numbers, we use the gcd algorithm to find the greatest common divisor of the two numbers. Multiply the two numbers and then divide the greatest common divisor to get the least common multiple. The code is as follows:

int lcm (int a,int b) {
    
    
	return a*b/gcd(a,b);
}

Expansion: gcd can find the greatest common divisor not only by rolling and dividing, but also by phase reduction, violent enumeration,
and phase reduction. The principle: two positive integers a and b (a>b), their greatest common divisor Equal to the greatest common divisor of the subtraction c of ab and the smaller number b.

//更相减损术
int gcd(int a,int b) {
    
    
	while (a != b) {
    
    
    	if (a > b) 
      		a -= b;
      	else 
      		b -= a;
  	}
  return a;
}

Comparison:
time complexity of violent enumeration: O(min(a,b));
time complexity of rolling and dividing: O(log(max(a,b)))
time complexity of phase reduction: O(max( a,b))
In contrast, the rolling and dividing method is more stable in O(log(N)). From a general point of view, there is no difference between the two in essence, but when there is a large difference between two numbers, we need It would take more subtractions to do it, but obviously, division is faster.
However, the modulus calculation performance of the rolling and dividing method is poor
, so in the actual coding process, it is still up to you to decide which method to use, but in general, the rolling and dividing method can meet most of the problems.

Guess you like

Origin blog.csdn.net/qq_48627750/article/details/119317999