Files
freeCodeCamp/curriculum/challenges/chinese/22-rosetta-code/rosetta-code-challenges/evaluate-binomial-coefficients.md
2024-01-24 19:52:36 +01:00

1.1 KiB
Raw Blame History

id, title, challengeType, forumTopicId, dashedName
id title challengeType forumTopicId dashedName
598de241872ef8353c58a7a2 评估二项式系数 1 302259 evaluate-binomial-coefficients

--description--

Write a function to calculate the binomial coefficient for the given value of n and k.

写一个函数来计算给定n和k值的二项式系数。

$\binom{n}{k} = \frac{n!}{(n-k)!k!} } = \ frac {nn-1n-2\ ldotsn-k + 1} { kk-1k-2\ ldots 1} $

--hints--

binom是一个功能。

assert(typeof binom === 'function');

binom(5,3)应该返回10。

assert.equal(binom(5, 3), 10);

binom(7,2)应该返回21。

assert.equal(binom(7, 2), 21);

binom(10,4)应该返回210。

assert.equal(binom(10, 4), 210);

binom(6,1)应该返回6。

assert.equal(binom(6, 1), 6);

binom(12,8)应该返回495。

assert.equal(binom(12, 8), 495);

--seed--

--seed-contents--

function binom(n, k) {

}

--solutions--

function binom(n, k) {
  let coeff = 1;
  for (let i = n - k + 1; i <= n; i++) coeff *= i;
  for (let i = 1; i <= k; i++) coeff /= i;
  return coeff;
}