43 lines
860 B
Text
43 lines
860 B
Text
CREATE OR REPLACE FUNCTION factorial_t(num) as table (
|
|
with recursive cte as (
|
|
select 0 as n, 1::DOUBLE as fact
|
|
union all
|
|
select
|
|
n+1 as n,
|
|
((n+1) * fact) as fact
|
|
from cte
|
|
where n < num
|
|
) select n, fact from cte
|
|
) ;
|
|
|
|
CREATE OR REPLACE FUNCTION left_factorial(num) as (
|
|
if (num < 1, 0,
|
|
(select sum(fact) from factorial_t(num - 1)) )
|
|
);
|
|
|
|
CREATE OR REPLACE FUNCTION left_factorial_t(num) as table (
|
|
with recursive cte as (
|
|
select 0 as n, 1.0::DOUBLE as fact, 0::DOUBLE as sum
|
|
union all
|
|
select
|
|
n+1 as n,
|
|
((n+1) * fact) as fact,
|
|
sum + fact as sum
|
|
from cte
|
|
where n < num
|
|
)
|
|
select n, sum as left_factorial
|
|
from cte
|
|
order by n
|
|
) ;
|
|
|
|
# First 10
|
|
from left_factorial_t(10);
|
|
|
|
# By 10s
|
|
from left_factorial_t(110)
|
|
where n % 10 = 0
|
|
and n > 10;
|
|
|
|
# Maximum is for 171
|
|
select left_factorial(171);
|