Number of combinations (N choose R) in C++

后端 未结 7 2363
日久生厌
日久生厌 2020-11-27 18:17

Here I try to write a program in C++ to find NCR. But I\'ve got a problem in the result. It is not correct. Can you help me find what the mistake is in the program?

相关标签:
7条回答
  • 2020-11-27 18:57

    A nice way to implement n-choose-k is to base it not on factorial, but on a "rising product" function which is closely related to the factorial.

    The rising_product(m, n) multiplies together m * (m + 1) * (m + 2) * ... * n, with rules for handling various corner cases, like n >= m, or n <= 1:

    See here for an implementation nCk as well as nPk as a intrinsic functions in an interpreted programming language written in C:

    static val rising_product(val m, val n)
    {
      val acc;
    
      if (lt(n, one))
        return one;
    
      if (ge(m, n))
        return one;
    
      if (lt(m, one))
        m = one;
    
      acc = m;
    
      m = plus(m, one);
    
      while (le(m, n)) {
        acc = mul(acc, m);
        m = plus(m, one);
      }
    
      return acc;
    }
    
    val n_choose_k(val n, val k)
    {
      val top = rising_product(plus(minus(n, k), one), n);
      val bottom = rising_product(one, k);
      return trunc(top, bottom);
    }
    
    val n_perm_k(val n, val k)
    {
      return rising_product(plus(minus(n, k), one), n);
    }
    

    This code doesn't use operators like + and < because it is type generic (the type val represents a value of any kinds, such as various kinds of numbers including "bignum" integers) and because it is written in C (no overloading), and because it is the basis for a Lisp-like language that doesn't have infix syntax.

    In spite of that, this n-choose-k implementation has a simple structure that is easy to follow.

    Legend: le: less than or equal; ge: greater than or equal; trunc: truncating division; plus: addition, mul: multiplication, one: a val typed constant for the number one.

    0 讨论(0)
提交回复
热议问题