zoukankan      html  css  js  c++  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

        }

       

    }

  • 相关阅读:
    【转载】以太网帧类型速查表
    oracle 无法解析指定的连接标识符
    最近观影有感~
    myeclipse 8.5 安装svn插件
    Symbian S60 设备配置 IMAP
    VS 2008 自动缩进修改
    RGB YUV [转]
    NoteExpress 无法访问国外数据库
    小s坐月子
    2011124 code
  • 原文地址:https://www.cnblogs.com/guet/p/3903103.html
Copyright © 2011-2022 走看看