Java编写最大公约数和最小公倍数
package javaapplication24;
class NegativeIntegerException extends Exception{
String message;
public NegativeIntegerException(){
message="方法的参数值不是正整数";}
public String toString(){
return message;}
}
class MaxCommonDivisor{
public int getMaxCommonDivisor(int a,int b)throws NegativeIntegerException{
if(a<0||b<0)
throw new NegativeIntegerException();
int r=0;
if(b>a){
int t=a;a=b;b=t;}
r=a%b;
while(r!=0){
a=b;
b=r;
r=a%b;}
return b;}}
class MinCommonMultiple extends MaxCommonDivisor{
public int getMinCommonMultiple(int a,int b) throws NegativeIntegerException{
if(a<0||b<0)
throw new NegativeIntegerException();
int y=0;
int x=getMaxCommonDivisor(a,b);
y=(a*b)/x;
return y;
}}
/**
*
* @author qingzhu
*/
public class JavaApplication24 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int maxCommonDivisor , minCommonMultiple;
MaxCommonDivisor max=new MaxCommonDivisor();
MinCommonMultiple min=new MinCommonMultiple();
try{maxCommonDivisor=max.getMaxCommonDivisor(18, 12);
System.out.println("最大公约数:"+maxCommonDivisor);
minCommonMultiple=min.getMinCommonMultiple(18, 12);
System.out.println("最小公倍数:"+minCommonMultiple);
maxCommonDivisor=max.getMaxCommonDivisor(-64,48);
System.out.println("最大公约数:"+maxCommonDivisor);
}
catch(NegativeIntegerException e){
System.out.println(e.toString());}
// TODO code application logic here
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。