Mihir
Mihir

Reputation: 8734

factorial of a number

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>

Upvotes: 10

Views: 85362

Answers (28)

krish
krish

Reputation: 1

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);

Upvotes: 0

Sandeep Gantait
Sandeep Gantait

Reputation: 875

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

console.log(fact(10))

Upvotes: 2

Debasis Panda
Debasis Panda

Reputation: 461

function factorial(n) {
    return [...Array(n + 1).keys()].slice(1).reduce((total, currentValue) => total * currentValue, 1);
}

Upvotes: 0

Redu
Redu

Reputation: 26181

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));

Upvotes: 1

Kunal
Kunal

Reputation: 131

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)

Upvotes: 0

Mohit
Mohit

Reputation: 331

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/

Upvotes: 0

Bijay Pal
Bijay Pal

Reputation: 251

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.

Upvotes: 1

Srikrushna
Srikrushna

Reputation: 4965

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));

Upvotes: 1

Aissam BAHARI
Aissam BAHARI

Reputation: 111

function factorial (n) {
  if (n > 1) {
    return n * factorial(n-1);
  }
  return 1;
}
console.log("recursive way => ",factorial(5)); 

Upvotes: 0

Neil Meyer
Neil Meyer

Reputation: 587

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.

Upvotes: 0

Javidan Akberov
Javidan Akberov

Reputation: 73

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.

Upvotes: 0

Mohsan Abbas
Mohsan Abbas

Reputation: 1

    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

Upvotes: 0

Aria5h4h
Aria5h4h

Reputation: 65

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>

Upvotes: 0

cssimsek
cssimsek

Reputation: 1265

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>

Upvotes: 1

Denys Medvediev
Denys Medvediev

Reputation: 1240

function factorial(n) {
  return (n != 1) ? n * factorial(n - 1) : 1;
}

alert( factorial(5) );

You can try to use recursion method

Upvotes: 5

Decebal
Decebal

Reputation: 1419

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];
 }

Upvotes: 0

Bhanu Pratap
Bhanu Pratap

Reputation: 1761

 <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... :)

Upvotes: 0

Jamshid Ajam
Jamshid Ajam

Reputation: 11

I wrote this and it works.

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

Upvotes: 1

Alex G
Alex G

Reputation: 1

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;
}

Upvotes: 0

ElectroBit
ElectroBit

Reputation: 1212

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.

Upvotes: 0

Anon Ymus
Anon Ymus

Reputation: 111

What about:

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

?

Upvotes: 0

Javed Akram
Javed Akram

Reputation: 15344

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))">

Upvotes: 5

Felix Kling
Felix Kling

Reputation: 816770

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;
}

Upvotes: 26

Kobi
Kobi

Reputation: 138087

  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

Upvotes: 3

Dan
Dan

Reputation: 2341

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)

Upvotes: 0

Anton
Anton

Reputation: 9961

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));">

Upvotes: 0

Flinsch
Flinsch

Reputation: 4340

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

Upvotes: 2

Douglas
Douglas

Reputation: 37761

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.

Upvotes: 0

Related Questions