描述
小明被一个问题给难住了,现在需要你帮帮忙。问题是:给出两个正整数,求出它们的最大公约数和最小公倍数。
-
输入
-
第一行输入一个整数n(0<n<=10000),表示有n组测试数据;
随后的n行输入两个整数i,j(0<i,j<=32767)。
输出
- 输出每组测试数据的最大公约数和最小公倍数 样例输入
-
3 6 6 12 11 33 22
样例输出
-
6 6 1 132 11 66 -
#include <iostream> using namespace std; void fun(int m,int n) { int temp,max = m,min = n;if(max < min){temp = max;max = min;min = temp;}do{temp = max % min;max = min;min = temp;}while(temp);cout<<max<<' '<<(m * n)/max<<endl; } int main(void) {int n,num1,num2;cin>>n;while(n--){cin>>num1>>num2;fun(num1,num2);} }#include <iostream> using namespace std; int main(void) {int n,i,j;cin>>n;while(n--){cin>>i>>j;int min = i < j? i : j;for(int step = i; ; step--){if((i % step == 0)&& (j % step == 0)){cout<<step<<' '<<(i*j)/step<<endl;break;}}} }
以上,关于公约数和公倍数的两种解法,第一种解法不用多说了,大家基本都知道,第二种,两个数当中,从最小数开始依次递减,遍历整数,找到最大的公约数!