---
# System prepended metadata

title: 'Java 學習筆記 - 2-3: 找出公因數'
tags: [Java 學習筆記]

---

###### tags: `Java 學習筆記`
# Java 學習筆記 - 2-3: 找出公因數
## 最小公因數開始排 (假設必定 n < k)
```java=
public class MainClass {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        for (int i = 1; i <= n; i++) {
            if (n % i == 0 && k % i == 0) {
                System.out.print(i + " ")
            }
        }
    }
}
```
## 最大公因數開始排 (假設必定 n < k)
```java=
public class MainClass {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int k = scanner.nextInt();
        for (int i = n; i >= 1; i--) {
            if (n % i == 0 && k % i == 0) {
                System.out.print(i + " ")
                // 如果在這邊寫 break 就只會印出最大公因數
            }
        }
    }
}
```