Greatest Common Divisor (GCD) problem

Topic 1: Find the greatest common divisor of two positive integers; (Greatest Common Divisor, GCD)

Question 2: Find the greatest common divisor of n positive integers;

Topic 3: Find the least common multiple of two positive integers; (Lowest Common Multiple, LCM)

Problem 4: Find the least common multiple of n positive integers.


The reason why these four problems are written together is that they all focus on the first problem: finding the greatest common divisor GCD of two numbers. The remaining three questions are based on it. There are two ways to calculate the greatest common divisor, and here is the first one: tossing and dividing.

Divide by turning and turning: take the larger of the two numbers as the dividend and the smaller number as the divisor, divide the larger number by the decimal, if the remainder is 0, then the smaller number is the greatest common divisor of the two numbers; if If the remainder is not 0, divide the remainder calculated in the previous step by the smaller number until the remainder is 0, then the greatest common divisor of these two numbers is the remainder in the previous step.

That is, for two numbers a,b (set a>b), if a%b=0, then gcd(a,b)=b; otherwise gcd(a,b)=gcd(b,a%b). Proof The process is very simple, omitted here.

//greatest common divisor of two numbers
int GCD(int a, int b) {
	return b == 0 ? a : GCD(b, a%b);
}

For the greatest common divisor of multiple numbers, just call the above GCD function in turn.

//greatest common divisor of n numbers
int GCD(vector<int>& g) {
	int ans = g[0];
	for (int i = 1; i < g.size(); i++)
		ans = GCD(ans, g[i]);
	return ans;
}

The calculation of the least common multiple of two numbers is based on the greatest common divisor, because for any two positive integers, the product of their greatest common divisor and the least common multiple is equal to the product of the two themselves. That is, a*b=lcm(a,b)*gcd(a,b).

// Least common multiple of two numbers
int LCM(int a, int b) {
	return a * b / GCD(a, b);
}

The least common multiple of multiple numbers can still be called by calling the LCM function in turn.

// Least common multiple of n numbers
int LCM(vector<int>& g) {
	int ans = g[0];
	for (int i = 1; i < g.size(); i++)
		years = LCM(years, g[i]);
	return ans;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325911842&siteId=291194637