javascript - Factoring numbers -


trying factor number i.e. 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040

started off haven't been able wrap head on how loop this:

function factorialize(num) {   (i = 1; < num; ++) {    var math = * i;     math++;    return math;  } } 

thank in advanced.

you have several mistakes in code ,, first multiply i*i ,, , increase math 1 ,, , return inside loop execute 1 iteration ,,

there several ways implement ,, i'll write down 2 of them

function get_factorial(num){    if(num < 0){       throw new rangeerror('factorial defined non-negative integers');    }    var res = 1;    for(var = num;num >1 ; num--){        res *= num;    }    return res; } 

and recursive way :

function get_factorial(num){     if(num < 0){       throw new rangeerror('factorial defined non-negative integers');     }     if(num ==1 || num ==0){       return 1;     }     return num * get_factorial(num-1); } 

** throwing exception in case of negative numbers instead of returning strings ,, based on paul suggestion


Comments