1. 程式人生 > 實用技巧 >Java 輾轉相除法求最大公約數

Java 輾轉相除法求最大公約數

import java.util.Scanner;

/**
 * @author guanlibin
 * @version 1.0
 * @since 2020/10/26 8:55
 */
public class T {
    public static void main(String[] args) {
        while (true) {
            Scanner sc = new Scanner(System.in);
            int a, b;
            try {
                // 輸入數a
                System.out.print("輸入數a:");
                a = sc.nextInt();
                // 輸入數a
                System.out.print("輸入數b:");
                b = sc.nextInt();
                // 始終保持a為大數
                int temp;
                if (a < b) {
                    temp = b;
                    b = a;
                    a = temp;
                }
                // 進行輾轉相除
                while (b != 0) {
                    temp = b;
                    b = a % b;
                    a = temp;
                }
                // 列印最大公約數
                System.out.printf("最大公約數為%s", a);
                System.out.println();
            } catch (Exception e) {
                System.out.println("您輸入的數字不合法");
            }
        }
    }
}