How Many Combinations?


Submit solution

Points: 40 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem types
Allowed languages
Java 19, Java 8

題目說明

請設計一程式,計算n取x有幾種組合

\(C_{x}^{n}={\frac {n!}{(n-x)!x!}}\)

輸入

兩正整數(分別為n、x,且n>=x
// n、x皆不大於15
// 若考量階乘數字過大,可使用long宣告變數

輸出

有幾種組合

測試資料 輸入

5 3

測試資料 輸出

10

Comments


  • 0
    scu09156146  commented on May 23, 2024, 12:20 p.m.

    題解

    import java.util.Scanner;
    
    public class Combination {
    
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int n = input.nextInt();
            int x = input.nextInt();
            input.close();
    
            // 調整x值,化簡階乘的複雜度
            x = Math.min(n - x, x);
    
            int ans;
            if (x == 0)
                ans = 1; // "n取0"只有1種組合
            else
                ans = factorial(n, x) / factorial(x, x); // 用副程式計算"n取x"有幾種組合
    
            // 印出答案
            System.out.print(ans);
    
        }
    
        public static int factorial(int start, int times) {
            // start:階乘的起始數字。times:需做幾次乘法。
            int result = start--;
            for (int i = 1; i < times; i++) {
                result = result * start--;
                // 乘完一次後,要對start做-1
            }
            return result;
        }
    
    }