factorial of a number

Use loop its easy to implement

function fact(num)
{
    if(num<0)
     return "Undefined";
    var fact=1;
    for(var i=num;i>1;i--)
      fact*=i;
    return fact;
 }

<input type="button" value="Find factiorial" onclick="alert(fact(6))">

You have to return the value. Here you go:

function fact(x) {
   if(x==0) {
      return 1;
   }
   return x * fact(x-1);
}

function run(number) {
    alert(fact(parseInt(number, 10)));
}

and

<input type="button" value="Find factiorial" onclick="run(txt1.value)">

(How to make it work for negative numbers I leave up to you ;) (but I showed in this post anyway))

Just for fun, a more correct, non recursive algorithm:

function fact(x) {
       if(x == 0) {
           return 1;
       }
       if(x < 0 ) {
           return undefined;
       }
       for(var i = x; --i; ) {
           x *= i;
       }
       return x;
}

Tags:

Javascript