二项式系数

发布于 2024-10-02 03:38:42 字数 433 浏览 0 评论 0原文

我一直在寻找一种简单的二项式系数算法,但无济于事。问题是我在课堂上使用的语言有点……奇怪。其中很多都是使用 Yacc 和 Lex。

不管怎样,我们在课堂上做了一个例子:

n=12; p=1; i=1;
while (i <= n) {
        p = p * i;
        print p;
        i = i + 1;
};

这是一个计算阶乘的例子,但现在我需要修改它以便能够计算 C(n,k) 或 N 选择 K (又名二项式系数),但我不知道如何复杂我应该做。我们可以选择任何 N 和 K(用户不必输入它们),因此任何随机的 2 个数字都可以工作(例如上面的示例)。我很确定这段代码只支持基本函数,例如 while 循环和基本数学,所以我认为使用阶乘是不可能的......但我想我可以使用上面的代码吗?

有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不疑不惑不回忆 2024-10-09 03:38:42

因为我假设这是家庭作业,所以我不会提供解决方案。我要说的是:

C(n,k) 有一个依赖于除法、减法、乘法和阶乘的公式:

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

您已经有了可以计算阶乘的代码,并且看起来您正在使用的语言支持您需要的其他数学运算符。

因此,您所要做的就是计算三个阶乘:一个用于 n,一个用于 k,一个用于 nk

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.

画尸师 2024-10-09 03:38:42

如果您需要插件库来完成这项工作,您始终可以使用 Boost 库: http://www.boost.org/doc/libs/1_35_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/factorials/sf_binomial .html

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文