求最大公约数(Greatest Common Divisor)

写在开头:数字A与数字B的最小公倍数等于数字A与数字B的积除以他们的最大公约数,即LCM(A,B)=(A*B)/GCD(A,B)。
以下为求最大公约数的两种方法:
法一(辗转相除法)

#include<iostream>
using namespace std;

int gcd(int a, int b)
{
 int c;
 while (b)
 {
  c = a%b;
  a = b;
  b = c;
 }
 return a;
}

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

法二(欧几里得递归算法)

#include<iostream>
using namespace std;

int gcd(int a, int b)
{
 return b == 0 ? a : gcd(b, a%b);
}

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

猜你喜欢

转载自blog.csdn.net/qq_43548474/article/details/88984432