求任意两个数的最大公因数和最小公倍数

有A和B两个整数

最大公因数:

    在A和B的因数中能同时整除A和B的最大的数。

    求法:辗转相除法(欧几里得算法)

int gcd(int m , int n){
    int r = 0 ;
    while(n){
        r = m%n;
        m = n;
        n = r;
    }
    return m;
}

在C++ algorithm头文件中,有__gcd(A,B)方法。

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
	int a, b;
	cin>>a>>b;
	cout<<__gcd(a,b)<<endl;
	return 0;
}


最小公倍数:

    A和B都能整除的最小的数。

    A和B的最小公倍数 = A*B / gcd(A,B);


猜你喜欢

转载自blog.csdn.net/adusts/article/details/80555461
今日推荐