二項式係數表 C 程式


給定一個正整數,例如 'val',任務是列印二項式係數 B(n, k) 的值,其中 n 和 k 是 0 到 val 之間的任意值,並顯示結果。

什麼是二項式係數

二項式係數 (n, k) 是從給定的 'n' 種可能性中選擇 'k' 個結果的順序。正 n 和 k 的二項式係數的值由下式給出

$$C_k^n=\frac{n!}{(n-k)!k!}$$

其中,n >= k

示例

Input-: B(9,2)
Output-:

$$B_2^9=\frac{9!}{(9-2)!2!}$$

$$\frac{9\times 8\times 7\times 6\times 5\times 4\times 3\times 2\times 1}{6\times 5\times 4\times 3\times 2\times 1)\times 2\times 1}=\frac{362,880}{1440}=252$$

什麼是二項式係數表

二項式係數表用於計算 n 和 k 之間可以生成的多個值。

示例

Input-: value = 5
Output-:

以下程式中使用的方案如下

  • 從使用者處輸入變數 'val' 以生成表格
  • 從 0 到 'val' 開始迴圈,因為二項式係數的值將在 0 到 'val' 之間
  • 如果 n 和 k 不為 0,則應用給定的公式

    B(m, x) = B(m, x - 1) * (m - x + 1) / x

  • 列印結果

演算法

START
Step 1-> declare function for binomial coefficient table
   int bin_table(int val)
   Loop For int i = 0 and i <= val and i++
      print i
      Declare int num = 1
      Loop For int j = 0 and j <= i and j++
      If (i != 0 && j != 0)
         set num = num * (i - j + 1) / j
      End
         print num
   End
   print 
Step 2-> In main()    Declare int value = 5    call bin_table(value) STOP

示例

#include <stdio.h>
// Function for binomial coefficient table
int bin_table(int val) {
   for (int i = 0; i <= val; i++) {
      printf("%2d", i);
      int num = 1;
      for (int j = 0; j <= i; j++) {
         if (i != 0 && j != 0)
         num = num * (i - j + 1) / j;
         printf("%4d", num);
      }
      printf("
");    } } int main() {    int value = 5;    bin_table(value);    return 0; }

輸出

更新於: 2020年7月9日

7K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告