加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 17:24:45 所属栏目:百科 来源:网络整理
导读: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、 用W

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读