以下用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