“异曲同工”看不同程序员如何编写阶乘函数
(*编程新手*) fact1[x_Integer]:=Which[x <1,Return[1],True,Return[x*fact1[x -1]]]; Print[fact1[10]] (*Pascal程序员*) fact2[x_]:=Module[{res =1,i =2},While[i<=x, res *= i; i = i +1];Return[res]]; Print[fact2[10]] (*C程序员*) fact3[x_]:=Module[{res =1, i},For[i=2, i <= x, i++, res *= i;];Return[res]]; Print[fact3[10]] (*看过SICP的程序员*) fact4[n_,t_:1]:=If[n ==0, t, fact4[n -1, t*n]];(*此处用了尾递归和默认参数*) Table[fact4[i],{i,10}] (*有一定Mathematica经验的程序员*) fact5[x_]:=Module[{res =1},Do[res *= i,{i, x}]; res]; (*Mathematica中不推荐用For或者While的,执行效率较低*) Table[fact5[i],{i,10}] (*懒惰的程序员*) fact6[x_]:=If[x <1,1, x*fact6[x -1]]; fact6 /@Range[10] (*更懒的*) fact7 =If[#<1,1,#*#0[#-1]]&; fact7 /@Range[10] (*数学系的*) fact8[1]=1; fact8[x_]:= x*fact8[x -1]; fact8 /@Range[10] (*Mathematica专家*) fact9 =FoldList[#1*#2&,1,Range[2,#]]&;(*类似Python里面的reduce*) fact9[10] (*黑客*) fact10 =Times@@Range[#]&; fact10~Map~Range@10 (*专家级别*) fact11[x_]:=Gamma[x +1] (*伽玛函数是作为阶乘的延拓,阶乘是其特例*) 10// fact11 (*大英帝国程序员*) fact12[x_]:=Product[i,{i,1, x}]; (*Product是连乘函数,阶乘当然是连乘*) fact12@10 (*喜欢恶搞的程序员*) fact13[x_]:=Length@Permutations@Range@x;(*x个元素的全排列长度为x!,很低效且占内存*) fact13@10 (*喜欢用模式匹配的人*) fact14[x_]:={1, x}//.{a_,b_/; b >0}:>{b a, b -1}//First; fact14[10] (*最懒的*) fact15 =#!&;(*!是专门计算阶乘的内置函数Factorial的简写*) fact15@Range@10
相关推荐
湾区人工智能 2020-11-20
diskingchuan 2020-10-23
amicablehj 2020-11-16
smartbaby 2020-11-11
teamvx 2020-11-11
啊兵 2020-11-10
ruancw 2020-11-10
Elyn 2020-11-08
susmote 2020-11-07
lipin 2020-11-03
kinglomei 2020-10-27
bucai 2020-10-26
JAVA飘香 2020-10-26
重剑无锋 2020-10-25
adentheima 2020-10-25
zhaoyinghuan 2020-10-25
Elyn 2020-10-24
lipin 2020-10-22
feinifi 2020-10-14