10

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>
Mihir
  • 8,696
  • 18
  • 56
  • 87

28 Answers28

26

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;
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • The recursive algorithm doesn't have a base case. The non-recursive function is wrong as well. – dheerosaur Dec 14 '10 at 10:42
  • @dheerosaur: Yep, for the recursive algorithm, fixed that (still early for me ;)). But why is the non-recursive one wrong? It works for me (see here http://jsfiddle.net/fgpPJ/1/) @Mihir: It works now. – Felix Kling Dec 14 '10 at 10:44
  • i found one thing.. when i place if(x>0){ return x* fact(x-1)} the result is NaN.. where as when i place if(x==0){return 1} return x*fact(x-1).. it is showing correct result. what is the difference between those two blocks of code – Mihir Dec 14 '10 at 10:46
  • Sorry, the non-recursive one is right. I was looking for the idiomatic check in `for`. – dheerosaur Dec 14 '10 at 10:47
  • @Mihir - in the second snippet, all code paths *return a number*. On the first, you need `return 1` after the `if` - it isn't a complete function without it. – Kobi Dec 14 '10 at 10:48
  • @Mihir: In the first, if `x` is equal to zero, the function will return nothing (`undefined`) because it only returns something if `x>0`. But number multiplied with `undefined` gives `undefined` (or `NaN` not sure). – Felix Kling Dec 14 '10 at 10:48
5
function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

alert( factorial(5) );

You can try to use recursion method

Denys Medvediev
  • 1,160
  • 3
  • 16
  • 32
5

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))">
Javed Akram
  • 15,024
  • 26
  • 81
  • 118
3
  1. Your function doesn't return anything, ever.
  2. What do you do when x is 0?
  3. Minor point - apart from alert, you don't really do anything with the returned value.

Try this instead, if you will (hover over the text):

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

Working example: http://jsbin.com/apuka3/2

Kobi
  • 135,331
  • 41
  • 252
  • 292
  • How do you create the hover effect? – Tomas Dec 14 '10 at 10:42
  • @Tomas: Start the line with `>!` - http://meta.stackexchange.com/questions/1191/add-markdown-support-for-hidden-until-you-click-text-aka-spoilers – Kobi Dec 14 '10 at 10:43
2

You need to have a return in your function in the first place. ;)

Flinsch
  • 4,296
  • 1
  • 20
  • 29
1

I wrote this and it works.

  var d = 1;
  for (num; num > 1; num--) {
    d *= num;
  }
  return d;
1

Here's a short recursive version:

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

function factorialFromInput() {
  var theInputVal = document.getElementsByTagName("input")[0].value;
  var theContainer = document.getElementById("resultContainer");
  theContainer.innerHTML = "" + doFact(Math.abs(theInputVal));
}
.wrapper>* {
  line-height: 2em;
  width: 30%;
}
#resultContainer {
  border: outset grey;
  min-height: 1.1em;
  padding-left: 0.3em;
  background-color: #eff0f1;
  overflow: scroll;
}
<div class="wrapper">
  <input type="text" id="valEntered">
  <br>
  <button onclick="factorialFromInput();">Calculate Factorial</button>
  <br>
  <div id="resultContainer"></div>
</div>
cssimsek
  • 1,255
  • 14
  • 20
1

Recursion in JS is open to stack overflow error and also very slow. Looping by other means is better. My contribution to factorial code would be a straightforward one;

var fact = n => n > 0 ? Array.from({length: n}, (_,i) => i+1)
                             .reduce((p,c) => p*c)
                      : 1;
console.log(fact(5));
Redu
  • 25,060
  • 6
  • 56
  • 76
1
function fact(n) {
  if (n > 1) {
    return n * fact(n-1);
  } else {
    return 1;
  }
}
console.log(fact(5));

Using ternary operator we replace the above code in a single line of code as below

function fact(n) {
      return (n != 1) ? n * fact(n - 1) : 1;
 }
console.log(fact(5));
Srikrushna
  • 4,366
  • 2
  • 39
  • 46
1

This is the very easiest way and latest JS(ES6)

factorial = n =>  n - 1 > 0 ? n * factorial(n - 1) : n;

//output
console.log(factorial(5));

Here I used ES6 arrow function. For better understanding please see what is arrow function.

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
Bijay Pal
  • 241
  • 3
  • 5
1

//This is fastest way to implement factorial
const fact = n => !n ? 1 : n * fact(--n);

console.log(fact(10))
Sandeep Gantait
  • 837
  • 8
  • 9
0

My suggestion:

function fact(x) {
    if (x<0) {
        return Infinity
    };
    var _= 1
    for ($=1;$<=x;++$) {
        _*=$
    };
    return _
};

It simply returns the factorial of whatever "x" is.

ElectroBit
  • 1,152
  • 11
  • 16
0

Here is one I made using a while loop:

function factorialize(num) 
{
  i = 1;
  b = 1;
  while (i < num) {
    b = b + (b * i);
    i = i + 1;
    }
return b;
}
Alex G
  • 1
  • 1
0
 <script src="jquery-3.1.0.js"></script>
<script>
    $(function () {
        var target = 5;
        var factorial = 1;
        for (var i = 1; i <= target; i++) {
            factorial *= i;
        }
        alert(factorial);
       });
</script>

you can set any value in target and this logic will calculate Factorial. click to see output screen

Thanks... :)

Bhanu Pratap
  • 1,635
  • 17
  • 17
0

I am not sure why no one used dynamic programming to answer this, it's by far the most efficient way to build something on a factorial in my view.

 var mem = [];

 function fact(num)
 {
    var x = parseInt(num);

    if (x == 0 || x == 1) return 1;

    mem[x] = x * fact(x-1);

    return mem[x];
 }
Decebal
  • 1,376
  • 1
  • 21
  • 36
0

a very simple form:

function fact() {
    var x = document.getElementById("txtf").value;
    var f=1;
    for (var i=1; i <= x ; i++){
        f = f*i;
    }
    document.getElementById('showR').innerHTML= f;
}


 <input type="text" id="txtf" value="3">
   <input type="button" id="btnf" value="click for calculate" onclick="fact()">
   <p id="showR">/Factoriel/</p>
Aria5h4h
  • 75
  • 2
  • 2
  • 12
0
    function factorial(num) {

    var result = 1;

    for (var i = 1; i <= num; i++) {
        result = result * i;

    }

    return result;
}
//call function e.g factorial(4).. 1*2*3*4 it will evaluate in ascending order
0

The important part of the function is this line:

 x = x * fact(x-1);

but the fact function does not return a value, so this is the same as x * undefined. Try adding return x; to the bottom of your function.

Douglas
  • 36,802
  • 9
  • 76
  • 89
0

1) When X=0 function should return 1; 2) Added return;

 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    else
        x=1;
    return x;
 }

usage

<input type="button" value="Find factiorial" onclick="alert(run(fact.value));">
Anton
  • 9,682
  • 11
  • 38
  • 68
0

A slight edit to Anton's code:

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

}

(factorial of a negative doesn't exist, but factorial of 0 is equal to 1, in this case, if a number is smaller than 0, the function will return null)

Dan
  • 2,321
  • 3
  • 27
  • 40
  • @JavedAkram Please [this question](http://stackoverflow.com/q/359494/535122) to understand what `===` means. – Dan Jul 08 '13 at 10:19
0
var factorialNumber , factorial=1;
factorialNumber=prompt("Factorial Number" , "write Factorial Number");
for(var i = 1; i<= factorialNumber;i++){
    factorial *= i;
}
alert(factorial);

The code above first defines two variables, factorialNumber and factorial. factorial is initialized with 1. factorialNumber will get the result of the prompt (a number is expected) and then, using a cycle, in each step, factorial is multiplied with the index of the step, which is represented by i. When successfully calculated, we show the result using alert.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • 3
    Please add an explanation to your code. Code only answers are generally frowned upon – Icepickle Jun 24 '17 at 14:42
  • How is my code? is it good? Did bi help? I checked it was not bad What's your idea? By the way i am 17 years old – Javidan Akberov Jun 24 '17 at 19:06
  • 2
    It is fine, however, it is nothing different than some of the other answers here. My remark was mainly that people like to get an explanation of what the code does, next to a working example – Icepickle Jun 24 '17 at 19:32
0

With a Do loop, it is pretty easy.

    <table>
    <tr>
        <th>Amount of integers</th>
        <th>Answer</th>
    </tr>
    <tr>
        <th><input id="int" type="number"/></th>
        <th><input id="answer" type="number"/></th>
    </tr>
</table>
<button onclick="calculate()">calculate</button>
<script>
    function calculate() {
        var input = document.getElementById("int").value;
        var int = 1;

        do {
            var product = int *= input;
            input--;
        } while (input > 0);
        answer.value = product;
    }
</script>

You first set a table to act as a way to input your variable and have a place to output the answer. You also add a button to execute your function.

The input variable is the value entered by the user. You also have int variable as a placeholder.

Inside the do loop you then another variable that is the product, it takes your placeholder variable and times it by the input. After this the input decrements, as long as input value is then greater than zero the loop keeps iterating.

Then at the end, it posts the answer to the 'answer' id tag in the table.

Neil Meyer
  • 473
  • 4
  • 15
0
function factorial(num){
    if(num<1||typeof num!=='number'){
    return undefined
  }
  if(num===1){
    return num
  }
    return num*factorial(num-1)
}
console.log(factorial(3))

https://jsfiddle.net/mohittadhiyal/6w64x0sL/10/

Kirk Beard
  • 9,569
  • 12
  • 43
  • 47
Mohit
  • 331
  • 3
  • 6
0
function factorial (n) {
  if (n > 1) {
    return n * factorial(n-1);
  }
  return 1;
}
console.log("recursive way => ",factorial(5)); 
0

I've seen a recursive approach used in many places (Eloquent JavaScript etc). Here, the function is called recursively until it reaches 0, which should not be the case. We should only call the function till it is >= 2 because the last number we need to multiply by is 1.

It's a very minor change, and probably does not matter. Curious to know what other people think of it. Assuming it is a valid positive integer.

/**
 * Popular approach - the recursive function is called till x is 0
 * 
 * @param x
 */
function popularFactorial(x) {
    console.log(x)
    if(x === 0) {
        return 1
    } else {
        return x * popularFactorial(x - 1)
    }
}
var result = popularFactorial(8)
console.log(result)

/**
 * Using this approach, the recursive function is called one less time
 * i.e till x is 1
 * 
 * @param x 
 */
function factorial(x) {
    console.log(x)
    if(x === 0) {
      return 1
    } else if(x >= 2) {
        return x * factorial(x - 1)
    }
    return x
}
var result = factorial(8)
console.log(result)
Kunal
  • 131
  • 4
0
function factorial(n) {
    return [...Array(n + 1).keys()].slice(1).reduce((total, currentValue) => total * currentValue, 1);
}
Debasis Panda
  • 433
  • 1
  • 6
  • 15
0

What about:

function fact(n) {
  n = Math.round(n);
  if (n < 2) {
    return 1;
  }
  else {
    return n * fact(n - 1);
  }
}

?

Anon Ymus
  • 111
  • 3
0

i am quite new to javascript and would be happy to know any improvements that could be made to this answer

var a = 1;
function factorial(num) {
    if (num == 0) {
        return 1;
    } else if (num < 0) {
        return undefined;
    } else {
    for(i = num; i > 0; i--){
        a *= i;
    }
    return a;
    }
}
var b = factorial(5);
console.log(b);
krish
  • 1
  • 1
  • Hi there. Welcome to stackoverflow. This should be a question instead of an answer. The answer section is just for answers. But you can create a new question and link to this post as a reference. – F. Müller Nov 11 '20 at 10:31