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.
by iteration
function f(n) { var r = n; while (--n) { r *= n; } return r; }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
Post a Comment