算法基础训练题(一)

来源:互联网 发布:淘宝客推广怎么样 编辑:程序博客网 时间:2024/05/24 01:43
C时间限制:1 毫秒 |  C内存限制:1 Kb
题目内容:
欧几里得算法求最大公约数欧几里得算法求最大公约数欧几里得算法求最大公约数重要的事情说三遍...必须使用这个算法欧几里德算法又称辗转相除法,用于计算两个正整数a,b的最大公约数。
输入描述
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line. 每一行输入两个整数a和b。Process to end of file.支持处理文件尾

输出描述
For each pair of input integers a and b you should output the gcd(a,b) and lcm(a,b) in one line, and with one line of output for each line in input. 对于每组输入,要求输出 最大公约数 和 最小公倍数 在同一行,用空格隔开。

输入样例
3 5

输出样例
1 15

程序代码

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int a,b;
while(cin>>a>>b){
int m=a*b;
if(a<b){
int temp=a;
    a=b;
    b=temp;
}
int temp;//辗转相除法,用大数对小数求余,再比较小数和余,用较大的除较小的,直到余==0,输出最后较小数即为最大公约数,这为辗转相除法,最小公倍数==两数之积除以最大公约数
while(b!=0){
if(a<b){
      temp=a;
    a=b;
    b=temp;
   }
  temp=a%b;
  a=b;
  b=temp;
}
cout<<a<<" "<<m/a<<endl;
}
return 0;

}

0 0
原创粉丝点击