java 輸入兩個正整數 m 和 n,求其最大公約數和最小公倍數

import java.util.Scanner;

/**
 * 在循環中,只要除數不等於 0,用較大數除以較小的數,將小的一個數做爲下一輪循環的 大數,取得的餘數做爲下一輪循環的較小的數,如此循環直到較小的數的值爲
 * 0,返回較大 的數,此數即爲最大公約數,最小公倍數爲兩數之積除以最大公約數。
 */
public class Test6 {
    public static void main(String[] args) {
        int a, b, m;
        Scanner s = new Scanner(System.in);
        System.out.print("鍵入一個整數: ");
        a = s.nextInt();
        System.out.print("再鍵入一個整數: ");
        b = s.nextInt();
        Deff cd = new Deff();
        m = cd.deff2(a, b);
        int n = a * b / m;
        System.out.println("最大公約數: " + m);
        System.out.println("最小公倍數: " + n);
    }
}

class Deff {
    
    /**
     * 循環方式
     * @param x
     * @param y
     * @return
     */
    public int deff(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;
    }
    
    /**
     * 遞歸方式
     * @param x
     * @param y
     * @return
     */
    public int deff2(int x, int y) {
        int t;
        if (x < y) {
            t = x;
            x = y;
            y = t;
        }
        if (y != 0) {
            if (x == y)
                return x;
            else {
                int k = x % y;
                x = y;
                y = k;
                return deff2(x, y);
            }
        }
        return x;
    }
}
相關文章
相關標籤/搜索