23 lines
584 B
Text
23 lines
584 B
Text
# Compute nCr naively using UHUGEINT
|
|
# The caller should ensure 2r < n
|
|
create or replace function nCr_(n, r) as
|
|
(with recursive cte as
|
|
(SELECT 1::UHUGEINT as c, n as numerator, 1::UHUGEINT as m
|
|
UNION ALL
|
|
SELECT (c * numerator / m) as c,
|
|
(numerator - 1) as numerator,
|
|
(m + 1) as m
|
|
FROM cte
|
|
WHERE m <= r)
|
|
SELECT last(c order by m)
|
|
FROM cte
|
|
);
|
|
|
|
create or replace function nCr(n,r) as (
|
|
if( n<r, error('nCr expects r <= n'),
|
|
if( 2*r <= n, nCr_(n,r),
|
|
nCr_(n, n-r) ) )
|
|
);
|
|
|
|
## Example:
|
|
select nCr(140,50);
|