首页 > 代码库 > Java编写最大公约数和最小公倍数

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

    }

   

}