#include<stdio.h>
int cdiv1(int a, int b)//最大公约数函数1
{
if(a==b)
{
return a;
}
else if(a<b)
{
return cdiv1(b-a,a);
}
else
{
return cdiv1(a-b,b);
}
}
int cdiv2(int a,int b)//最大公约数2
{
if(a<b)
{
int temp=a;
a=b;
b=temp;
}
while(a%b)
{
int r=a%b;
a=b;
b=r;
}
return b;
}
int cpow(int a,int b)//最小公倍数函数
{
int ret=cdiv1(a,b);
return (a*b)/ret;
}
int main()
{
printf("最大公约数是 %d\n",cdiv1(6,8));
printf("最小公倍数是 %d\n",cpow(6,8));
return 0;
}
优化之后:
//实现求最小公约数
#include<stdio.h>
int main()
{
int a=6,b=8;
while(b)//以下循环中可以将a,b交换
{
int r=a%b;
a=b;
b=r;
}
printf("%d\n",a);
return 0;
}#include <iostream>
using namespace std;
int Least_Common_Multip(int a,int b)
{
while(b)
{
int tmp =a%b;
a=b;
b=tmp;
}
return a;
}
int Great_Common_Divisor(int a,int b)
{
int tmp = a*b;
while(b)
{
int t=a%b;
a=b;
b=t;
}
return (tmp/a);//return(tmp/Least_Common_Multip(a,b));
}
int main()
{
cout<<Least_Common_Multip(6,8)<<endl;
cout<<Great_Common_Divisor(6,8)<<endl;
}
本文探讨了在编程中实现最大公约数、最小公倍数等数学概念的优化算法,通过改进循环结构和函数调用,提高了计算效率。同时,详细介绍了求最小公约数、最大公约数及最小公倍数的实现方法,提供了简洁高效的代码实例。
903

被折叠的 条评论
为什么被折叠?



