gcd euclid
What is GCD?
什么是GCD?
It is called as a greatest common factor or generally called as a highest common factor (HCF). For example, if we take two numbers 4 and 6 then the factors of these numbers are 1,2,2 and 1,2,3 so the common factors are 2 and 1 and multiplication of these common factors is what we call as gcd of these two numbers which in the above case is 2 X 1 =2 so GCD (4,6) = 2.
它被称为最大公因子或通常被称为最高公因子(HCF)。 例如,如果我们取两个数字4和6,那么这些数字的因数是1,2,2和1,2,3,因此公因数是2和1 ,这些公因数的乘积就是我们所说的gcd这两个数字在上面的情况下是2 X 1 = 2,所以GCD(4,6)= 2 。
Basic Euclidean Algorithm for GCD:
GCD的基本欧几里得算法:
The above algorithm stands on two basic facts which are stated below:
上面的算法基于以下两个基本事实:
If we try to decrease the bigger number by subtracting that number by the small then the gcd remains unaffected.
如果我们尝试通过将数字减去小数字来减小数字,则gcd不会受到影响。
The base case in our algorithm is when we divide the smaller number and remainder comes out to be zero then our algo stops.
我们算法的基本情况是,当我们将较小的数除而余数变为零时,算法停止。
Description: So basically avoid all the brute force approaches we can perform the required task in O(log(min(a,b)) time using Euclid's algorithm which is an optimized approach as compared to the other approaches.
描述:因此,基本上避免了所有蛮力方法,我们可以使用Euclid算法在O(log(min(a(b,b)))时间内完成所需的任务,这是与其他方法相比的一种优化方法。
C ++程序使用EUCLID的算法查找两个数字的GCD (C++ program to find GCD of two numbers using EUCLID'S ALGORITHM)
#include<iostream>
using namespace std;
int euclidalgo(int x,int y)
{
if(x==0)
return y;
return euclidalgo(y%x,x);
}
int main()
{
int a,b;
cout<<"Enter two numbers whose GCD is to be calculated: ";
cin>>a>>b;
cout<<"GCD of these numbers is: "<<euclidalgo(a,b)<<endl;
return 0;
}
Output
输出量
Enter two numbers whose GCD is to be calculated: 4 6
GCD of these numbers is: 2
gcd euclid