求最小公倍数算法:
最小公倍数=两整数的乘积÷最大公约数
求最大公约数算法:
(1)辗转相除法
有两整数a和b:
① a%b得余数c
② 若c=0,则b即为两数的最大公约数
③ 若c≠0,则a=b,b=c,再回去执行①
函数 myfunc 接受两个正整数a,b
经过运算后打印出 它们的最大公约数和最小公倍数。
此时,调用 fun(15,20)
将会输出:
5
60
5
60
#include<stdio.h>
int a,b;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void fun(int a,int b)
{
int m,n,r;
if(a<b) swap(&a,&b);
m=a;n=b;r=a%b;
while(r!=0)//辗转相除法
{
a=b;b=r;
r=a%b;
}
printf("%d\n",b);//最大公约数
printf("%d\n",m*n/b);//最小公倍数
}
main()
{
scanf("%d %d",&a,&b);
fun(a,b);
return 0;
}
int a,b;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void fun(int a,int b)
{
int m,n,r;
if(a<b) swap(&a,&b);
m=a;n=b;r=a%b;
while(r!=0)//辗转相除法
{
a=b;b=r;
r=a%b;
}
printf("%d\n",b);//最大公约数
printf("%d\n",m*n/b);//最小公倍数
}
main()
{
scanf("%d %d",&a,&b);
fun(a,b);
return 0;
}