`
universsky
  • 浏览: 91299 次
文章分类
社区版块
存档分类
最新评论

50道Java 编程题 算法 源代码全说明 -- 求最大公约数和最小公倍数 东海陈光剑

 
阅读更多

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1;

/**
*题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
/**在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为0,返回较大的数,此数即为最大公约数,最小公倍数为两数之积除以最大公约数。* /

* @author cWX166129
*/
import java.util.*;
public class greatest_common_divisor {

public static void main(String[] args)
{
int a,b,m;
Scanner s=new Scanner(System.in);
System.out.println("Please input a: ");
a=s.nextInt();

System.out.println("Please input b: ");
b=s.nextInt();
//调用主实现类 greatestCommonDivisor
greatestCommonDivisor g=new greatestCommonDivisor();
//调用主实现类 greatestCommonDivisor里面的主方法
m=g.getGreatestCommonDivisor(a, b);
int n=a*b/m;

System.out.println("最大公约数: " + m);
System.out.println("最小公倍数: " + n);
}

}


//主实现类

class greatestCommonDivisor{
// 主方法
public int getGreatestCommonDivisor(int x, int y){

int t;
if (x<y){
t=x;
x=y;
y=t;
}
while(y!=0){
if (x==y) return x;
else{
int k=x%y;
x=y;
y=k;
}
}
return x;
}

}


//////////////////////////////////////////////////

run:
Please input a:
148
Please input b:
2068
最大公约数: 4
最小公倍数: 76516
成功构建 (总时间: 6 秒)

/**
*
*/
package iSword;

import java.util.Scanner;

/**
* @author cWX166129
*
*/
public class commonDivisorAndMultiple {

/**
* @param args
* 题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
/**在循环中,只要除数不等于0,用较大数除以较小的数,将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,如此循环直到较小的数的值为0,返回较大的数,此数即为最大公约数,最小公倍数为两数之积除以最大公约数。* /

*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a,b,m;
Scanner s=new Scanner(System.in);
System.out.print("Please input a:");
a=s.nextInt();
System.out.print("Please input b:");
b=s.nextInt();

getGreatestCommonDivisor g=new getGreatestCommonDivisor();
m=g.getGreatestCommonDivisor(a, b);
int n=a*b/m;

System.out.println("最大公约数: " + m);
System.out.println("最小公倍数: " + n);

}

}


class getGreatestCommonDivisor{

public int getGreatestCommonDivisor(int x,int y){
//getGreatestCommonDivisor g=new getGreatestCommonDivisor();
if(x<y)
//g.exChange(x,y);//交换大小

{
int t=x;
x=y;
y=t;
}

while(y!=0){
if(x==y) return x;

else
//g.tossDivide(x,y);//辗转相除法

{
int t=x%y;
x=y;
y=t;

}

}

return x;

}

public void exChange(int j,int k){
int t=j;
j=k;
k=t;
}
/*
* 辗转相除法
*
*/
public void tossDivide(int x, int y){
int k=x%y;
x=y;
y=k;
}


}

/////////////////////////////////

Please input a:666
Please input b:999
最大公约数: 333
最小公倍数: 1998

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics