mirror of
https://github.com/pragma-/pbot.git
synced 2025-01-10 03:52:34 +01:00
applets/qrpn: Fixed nchoosek implementation (#70)
This commit is contained in:
parent
2cf09ca415
commit
9d420fd5c9
@ -13,6 +13,7 @@
|
|||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <float.h>
|
#include <float.h>
|
||||||
#include <complex.h>
|
#include <complex.h>
|
||||||
|
#include <limits.h>
|
||||||
|
|
||||||
/* begin simple math functions we want to expose via the interpreter */
|
/* begin simple math functions we want to expose via the interpreter */
|
||||||
|
|
||||||
@ -74,12 +75,16 @@ static unsigned long long gcd(unsigned long long a, unsigned long long b) {
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
|
|
||||||
static unsigned long long nchoosek(const unsigned long long n, const unsigned long long k) {
|
static unsigned long long nchoosek(unsigned long long n, const unsigned long long k) {
|
||||||
if (1 == k) return n;
|
|
||||||
if (k > n - k) return nchoosek(n, n - k);
|
if (k > n - k) return nchoosek(n, n - k);
|
||||||
unsigned long long n_choose_k = n * (n - 1) / 2;
|
|
||||||
for (size_t kr = 3; kr <= k; kr++)
|
unsigned long long n_choose_k = 1;
|
||||||
n_choose_k *= (n + 1 - kr) / kr;
|
for (unsigned long long i = 1; i <= k; i++, n--) {
|
||||||
|
/* give up */
|
||||||
|
if (n_choose_k / i > ULLONG_MAX / n) return 0;
|
||||||
|
|
||||||
|
n_choose_k = n_choose_k / i * n + n_choose_k % i * n / i;
|
||||||
|
}
|
||||||
|
|
||||||
return n_choose_k;
|
return n_choose_k;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user