algorithm - Javascript Code improvement - Integer factorial -


i learning code javascript , 1 exercise returning factorial of provided integer. example: 5! = 1 * 2 * 3 * 4 * 5 = 120

i came result , accepted. however, not sure efficient way of solving this.

anyone have tips on how improve code?

function factorialize(num) {     var array = [];       (i = 1; <= num; i++) {         array.push(i);     }     var multi = 1;     (var = 1; < array.length; i++) {         multi *= array[i];     }     return multi; }  

many thanks!!

you have several approaches solution.

  1. by iteration

    function f(n) {     var r = n;     while (--n) {         r *= n;     }     return r; } 
  2. by recursion

    function f(n) {     return n === 0 ? 1 : n * f(n - 1); } 

    or short version

    function f(n) {     return +!~-n || n * f(n - 1); } 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

json - Gson().fromJson(jsonResult, Myobject.class) return values in 0's -