开发者

Binomial coefficient

I've been looking around trying to find a simple binomial coefficient algorithm, to no avail. The problem is the language I'm using for class is a bit... odd. A lot of it is using Yacc and Lex.

Anyways we did an example in class:

n=12; p=1; i=1开发者_如何学运维;
while (i <= n) {
        p = p * i;
        print p;
        i = i + 1;
};

This was an example of computing factorials, but now I need to modify it to be able to compute C(n,k) or N choose K (aka binomial coefficient), but I don't how complicated I should make it. We can choose any N and K (the user doesn't have to input them) so any random 2 numbers will work (such as the example above). I'm pretty sure this code only supports basic functions such as while loops and basic math, so I don't think using a factorial is possible... but I suppose I could use the above code as such?

Any ideas?


Since I'm assuming this is homework I'm not going to provide a solution. What I will say is this:

There is a formula for C(n,k) which relies on division, subtraction, multiplication and factorial:

n!/(k!(n-k)!)

You already have code that can calculate the factorial, and it looks like the language you are using supports the other math operators you need.

So all you have to do is compute three factorials: one for n, one for k and one for n-k.


You could always use the Boost library if you need a plugin lib to do the job for you: http://www.boost.org/doc/libs/1_35_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/factorials/sf_binomial.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜