输入两个正整数m和n,求其最大公约数和最小公倍数
(way1:选择结构)
#include<stdio.h>
#include<math.h>
int main()
{
int t,m,n,r,p;
scanf("%d %d",&m,&n);
p=m*n;
if(m<n)
{
t=m;
m=n;
n=t;
}
r=m%n;
while(r!=0)
{
m=n;
n=r;
r=m%n;
}
printf("最大公约数:%d\n最小公倍数:%d",n,p/n);
return 0;
}
(way2:函数)
#include<stdio.h>
int gcd(int m,int n)
{
int r;
while(r!=0)
{
r=m%n;m=n;
n=r;
r=m%n;
}
return n;
}
int lce(int m,int n)
{
return m*n/gcd(m,n);
}
int main()
{
int x,y,g;
scanf("%d%d",&x,&y);
g=gcd(x,y);
printf("hcf=%d\nlcd=%d",g,lce(x,y));
return 0;
}
(way3:函数递归)
#include<stdio.h>
int gcd(int m,int n) //最大公约数运用递归
{
int r;
r=m%n;
if(r==0) return n;
else return gcd(n,r);
}
int lce(int m,int n)
{
return m*n/gcd(m,n);
}
int main()
{
int x,y,g;
scanf("%d%d",&x,&y);
g=gcd(x,y);
printf("hcf=%d\nlcd=%d",g,lce(x,y));
return 0;
}