stdlib-js / stdlib-js/stdlib

update efficiency of calculating binomial coefficients

Offen
#2,442 4 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
JavaScript
Sterne
6k
Forks
1.3k
Ø Merge
1 T. 3 Std.
Gemergte PRs (30 T.)
611

Beschreibung

I can make a formal PR/Issue, but just sitting on my phone talking with chatGPT trying to figure out how to efficiently calculate binomial coefficients,I was looking at how you solve binomial coefficients in this package; @stdlib/math-base-special-binomcoef, and was wondering if a solution such as this would be better?

```ts
function binomialCoefficientLog(n, k) {
if (k > n) return 0;
if (k === 0 || k === n) return 1;

let logSum = 0;
for (let i = 0; i < k; i++) {
logSum += Math.log(n - i) - Math.log(i + 1);
}

return Math.exp(logSum);
}
```

This basically breaks it down to it's most simplest form (with log for maintaining precision) by stopping the loop once we reach k, so only calculating necessary values. Basically O(k) time complexity and O(1) space complexity.

Obviously error handling would need to be added but in a nutshell this is what I was thinking.

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.