Description
求两个正整数m和n的最大公约数(greatest common divisor)和最小公倍数(least common multiple)。
普及一下知识:
1. 求GCD用"辗转相除法"的运行速度比"枚举法"快得多。
2. 最小公倍数 = m * n / 最大公约数。
Input
有多个测试用例,一个测试用例占一行,是两个正整数m和n( 0 < m, n ≤ 100000 ),一个空格隔开。
m=-1 n=-1 表示结束。
Output
对每个测试用例输出一行,分别是m和n的最大公约数和最小公倍数,用一个空格分隔。
Sample Input
5 10
6 9
-1 -1
Sample Output
5 10
3 18
Hint
1. 枚举法,根据最大公约数、最小公倍数的定义,逐个数去试。速度较慢。
2. 用“辗转相除法”求出a,b的最大公约数c,a*b/c即最小公倍数。速度较快。
#include<stdio.h> int main() { int a,b,product; int temp; int r = 1; while (scanf("%d %d",&a,&b)!=EOF) { if(a==-1&&b==-1) { return 0; } if(0<a&&b<=100000) { product=a*b; if(a<b) { temp=a; a=b; b=temp; } while(r != 0) { r=a%b; a=b; b=r; } printf("%d ",a); printf("%d\n",product/a); } r=1;a=0;temp=0;product=0;b=10; } }