阶乘,即5! = 5*4*3*2*1, 先看传统的做法,利用while循环实现:
function factorial(num){ var result = num; if(num<0){ return -1; //负数返回-1 } if(num == 0){ return 1; // 0阶乘为1 } while(num-- >2){ result = result*num; } return result; }
javascript递归函数通过它调用其本身,利用递归的思路的话,阶乘的思路应该是 factorial(num)*factorial(num-1)*factorial(num-2) … factorial(0),即每次把num-1后作为参数调用自身:
function factorial2(num){ if(num <0){ return -1; } if(num == 0){ return 1; } return num*(factorial2(num-1)); }