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)=

參考輸出如下圖。

遞迴參考解答。

  1. #include
  2. using namespace std;
  3. int combination(int n, int r)
  4. {
  5. if (n == r || r == 0)
  6. return 1;
  7. else
  8. return combination(n - 1, r) + combination(n - 1, r - 1);
  9. }
  10. int main()
  11. {
  12. int n, r;
  13. cout << "計算組合數C,請輸入n、r:";
  14. cin >> n >> r;
  15. cout << "C(" << n << "," << r << ") = " << combination(n, r) << endl;
  16. system("pause");
  17. return 0;
  18. }

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

  1. #include
  2. using namespace std;
  3. int combination(int n, int r)
  4. {
  5. int total1 = 1, total2 = 1, total3 = 1;
  6. for (int i = 1; i <= n; i++)
  7. total1 *= i;
  8. for (int i = 1; i <= n - r; i++)
  9. total2 *= i;
  10. for (int i = 1; i <= r; i++)
  11. total3 *= i;
  12. return total1 / (total2 * total3);
  13. }
  14. int main()
  15. {
  16. int n, r;
  17. cout << "計算組合數C,請輸入n、r:";
  18. cin >> n >> r;
  19. cout << "C(" << n << "," << r << ") = " << combination(n, r) << endl;
  20. system("pause");
  21. return 0;
  22. }

留言

這個網誌中的熱門文章

C# 井字遊戲