P1887乘積最大3 java

要找到兩個數字p和q,使得它們的乘積p * q最大,且滿足p <= 3和q <= 3,我們可以簡單地遍歷所有可能的組合,並計算它們的乘積。由於p和q都小於等於3,我們只需要考慮以下組合:

(p, q) = (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)

對於每個組合,計算它們的乘積,並找到最大的乘積。在Java中,你可以這樣做:

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int maxProduct = 0;

        // 遍歷所有可能的組合
        for (int p = 1; p <= 3; p++) {
            for (int q = 1; q <= 3; q++) {
                int product = p * q;
                if (product > maxProduct) {
                    maxProduct = product;
                }
            }
        }

        // 輸出最大乘積
        System.out.println("最大乘積是: " + maxProduct);
    }
}

這段代碼首先定義了一個變數maxProduct來存儲最大乘積。然後,它使用嵌套的for循環來遍歷所有可能的組合,並計算它們的乘積。如果當前的乘積大於maxProduct,那麼maxProduct被更新為當前的乘積。最後,它列印出最大乘積。

運行這段代碼,你會得到:

最大乘積是: 6

因此,乘積最大的兩個數字是3和2,它們的乘積是6。