Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

factorial of a number

Tags:

javascript

I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
like image 487
Mihir Avatar asked Dec 14 '10 10:12

Mihir


People also ask

What is a factorial of 7?

7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040.

What is the factorial number of 12?

What is the Factorial of 12? 12! = 479001600.

What is a factorial example?

Factorials (!) are products of every whole number from 1 to n. In other words, take the number and multiply through to 1. For example: If n is 3, then 3! is 3 x 2 x 1 = 6.


1 Answers

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;
}
like image 193
Felix Kling Avatar answered Oct 20 '22 20:10

Felix Kling