浅谈求最大公约数最小公倍数

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值