【原创】PostgreSQL 实现阶乘方法列举

前端之家收集整理的这篇文章主要介绍了【原创】PostgreSQL 实现阶乘方法列举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Postgresql 功能庞大,对实现乘法这类运算有诸多的方法,今天我来简单列举下以下几种便捷的途径。

比如我们要计算10!


1、 可以用sql给它展开:

t_girl=#select1*2*3*4*5*6*7*8*9*10asmultiply_10;
multiply_10
------------
3628800
(1row)
Time:0.854ms


2、 用WITH递归

t_girl=#withrecursiveg(m,n)as
t_girl-#(select1m,10n
t_girl(#unionall
t_girl(#selectm*n,(n-1)nfromgwheren>1
t_girl(#)
t_girl-#selectmax(m)asfactorial_10fromg;
factorial_10
--------------
3628800
(1row)
Time:3.893ms

3、 用简单的函数来展开

createorreplacefunctionfunc_get_factorial(
f_numberint
)returnsbigint
as
$ytt$
declareiint:=1;
declarev_resultbigint:=1;
begin
foriin1..f_numberloop
v_result:=v_result*i;
endloop;
returnv_result;
end;
$ytt$
languageplpgsql;
t_girl=#selectfunc_get_factorial(10)asfactorial_10;
factorial_10
--------------
3628800
(1row)
Time:1.022ms


4、 用游标和序列函数generate_series来展开

createorreplacefunctionfunc_get_factorial2(
f_numberint
)returnsbigint
as
$ytt$
declarecs1cursorforselectnfromgenerate_series(1,f_number,1)asg(n);
declarev_resultbigint:=1;
declarev_nbigint:=0;
begin
opencs1;
loop
fetchcs1intov_n;
exitwhennotfound;
v_result:=v_result*v_n;
endloop;
closecs1;
returnv_result;
end;
$ytt$
languageplpgsql;
t_girl=#selectfunc_get_factorial2(10)factorial_10;
factorial_10
--------------
3628800
(1row)
Time:2.238ms
t_girl=#



5、 用自定义python函数

createorreplacefunctionfunc_get_factorial_py(
f_numberint
)returnsbigint
as
$ytt$
m=1
n=1
foriinrange(1,f_number+1):
m=m*i
n=m
returnn
$ytt$
languageplpythonu;
t_girl=#selectfunc_get_factorial_py(10)factorial_10;
factorial_10
--------------
3628800
(1row)
Time:1.060ms

猜你在找的Postgre SQL相关文章