算法基础训练题(一)

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;

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值