您的位置:首页 > 编程语言 > C语言/C++

C/C++训练1---最大公约数与最小公倍数

2017-10-29 17:25 309 查看
Problem Description

输入两个整数,求它们的最大公约数与最小公倍数。

Input

输入两个整数,两个整数之间用空格分开。

Output

第一行输出最大公约数;

第二行输出最小公倍数。

Example Input

64 48

Example Output

16

192

辗转相除法求最大公约数

while循环:

#include <iostream>
using namespace std;
#include <cstdio>
int main()
{
int a,b;
int r;
int x,y;
scanf("%d %d",&a,&b);
x=a;
y=b;
if(a<b)//先排序。大数在前
{
int t;
t=a;
a=b;
b=t;
}
while(b!=0)//求最大公约数:辗转相除法
{
r=a%b;
a=b;
b=r;
}
printf("%d\n%d\n",a,x*y/a);//最小公倍数:两数乘积除以最大公约数
return 0;
}


for循环:

#include <iostream>
using namespace std;
#include <cstdio>
int main()
{
int a,b;
int r;
int x,y;
scanf("%d %d",&a,&b);
x=a;
y=b;
if(a<b)//先排序。大数在前
{
int t;
t=a;
a=b;
b=t;
}
for(; b!=0;) //求最大公约数:辗转相除法
{
r=a%b;
a=b;
b=r;
}
printf("%d\n%d\n",a,x*y/a);//最小公倍数:两数乘积除以最大公约数
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: