求2个整数的公倍数和公约数

以下用2种方法求最大公约数和最小公倍数


package jk;

public class DataTest {

	/**
	 * @param args
	 * @author jake20001@126.com
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	/*	diviserAndmultiple dam = new diviserAndmultiple(4,18);
		System.out.println("max common diviser = " + dam.commonDiviser());
		System.out.println("min common multiple = " + dam.commonMultiple1());*/
		diviserAndmultiple2 dam = new diviserAndmultiple2();
		System.out.println("max common diviser = " + dam.commonDiviser2(4, 18));
		System.out.println("max common multiple = " + dam.commonMultiple2(4, 18));
	}

}

//以下是一般的算法
class diviserAndmultiple{
	int x;
	int y;
	int ax;
	int ay;
	public diviserAndmultiple(int x,int y){
		this.x = x;
		this.y = y;
		ax = x;
		ay = y;
	}
	//辗转相除法求公约数
	public int commonDiviser(){
		if(x>y){
			int temp = x;
			x = y;
			y = temp;
		}
		
		while((y%x)!=0){
			int temp2 = x;
			x = y%x;
			y = temp2;
		}
		
		return x;
	}
	//公倍数第1种求法
	public int commonMultiple(){
		int cm = ax*ay/commonDiviser();
		
		return cm;
	}
	//公倍数第2种求法
	public int commonMultiple1(){
		if(ax>ay){
			int temp = ax;
			ax = ay;
			ay = temp;
		}
		
		for(int i=1;i<=ax;i++){
			if(((i*ay)%ax)==0){
				return i*ay;
			}
		}
		
		return 0;
	}
}

//下面的方法是递归算法
class diviserAndmultiple2{

	public diviserAndmultiple2(){
	}
	//公约数
	public int commonDiviser2(int x,int y){
		if(x>y){
			int temp = x;
			y = x;
			x = temp;
		}
		if(y%x==0){
			return x;
		}
		return commonDiviser2(y%x,x);
	}
	//公倍数
	public int commonMultiple2(int x,int y){
		int i=1;
		if(x>y){
			int temp = x;
			y = x;
			x = temp;
		}
		
		if((y*i)%x==0){
			return y*i;
		}
		i++;
		
		return commonMultiple2(x,y*i);
	}
}

输出

max common diviser = 2
max common multiple = 36

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值