C++ HW4-4 HW4-5 for WallPower

排列組合中,從n個相異物取r個物件記做 C(n,r),其值可用數學遞迴定義如右:C(n,r) = C(n-1,r) + C(n-1,r-1)。以此定義寫出一C++程式,輸入正整數nr的值求以此定義寫出一C++程式求C(n,r)=

參考輸出如下圖。

遞迴參考解答。

#include 
using namespace std;

int combination(int n, int r)
{
 if (n == r || r == 0)
  return 1;
 else
  return combination(n - 1, r) + combination(n - 1, r - 1);
}

int main()
{
 int n, r;
 cout << "計算組合數C,請輸入n、r:";
 cin >> n >> r;
 cout << "C(" << n << "," << r << ") = " << combination(n, r) << endl;
 system("pause");
 return 0;
}

承上題,以函數呼叫與迴圈方式寫出C++程式。
數學公式:C(n,r) = n! / ((n-r)! * r!)
迴圈參考解答。

#include 
using namespace std;

int combination(int n, int r)
{
 int total1 = 1, total2 = 1, total3 = 1;
 for (int i = 1; i <= n; i++)
  total1 *= i;
 for (int i = 1; i <= n - r; i++)
  total2 *= i;
 for (int i = 1; i <= r; i++)
  total3 *= i;
 return total1 / (total2 * total3);
}

int main()
{
 int n, r;
 cout << "計算組合數C,請輸入n、r:";
 cin >> n >> r;
 cout << "C(" << n << "," << r << ") = " << combination(n, r) << endl;
 system("pause");
 return 0;
}

留言

這個網誌中的熱門文章

C# 井字遊戲