I want to write a factorial function in javascript. I have tried the following:
function factorial(n){
if(n==1){
return 1;
} else {
while(n>=0){
n = n * (n-1);
}
return n;
}
}
It is not working.
I want to write a factorial function in javascript. I have tried the following:
function factorial(n){
if(n==1){
return 1;
} else {
while(n>=0){
n = n * (n-1);
}
return n;
}
}
It is not working.
First return 1 for number 0 and 1 input number. If number is greater than 1 then iterate from 2 to input number and multiple result * i;
store into result variable.
function factorial(number) {
let result = 1;
for (let i = 2; i <= number; i++) {
result = result * i;
}
return result;
}
We can do it in the following way:
const factorial = (num: number): number => (num === 0) ? 1 : (num * factorial(num - 1));
You used while(n>=0)
instead of while(n>=2)
. Using n>=0
will make the end of the while loop multiply n
by 0
. You should also use the ===
operator to prevent values that are not numeric. You also forgot to decrease n
in the while
loop. Try one of the following:
Iteration method:
function factorial(n){
var result = n;
if(n<0){
return null;
}
if(n===1||n===0){
return 1;
} else {
while(n>=2){
result = result * (n-1);
n--;
}
return result;
}
}
<script>
function factorial(n){
var result = n;
if(n<0){
return null;
}
if(n===1||n===0){
return 1;
} else {
while(n>=2){
result = result * (n-1);
n--;
}
return result;
}
}
function calculate(){
var input = document.getElementById("number").value;
if(!isNaN(input)&&input.trim().length){
document.getElementById("result").innerHTML = factorial(parseInt(input, 10));
} else {
document.getElementById("result").innerHTML = "<b style='color: red;'>Input must be a number!</b>";
}
}
</script>
<input type="text" id="number" onkeyup="calculate()">
<br/>
<span id="result"></span>
Recursive method:
function factorial(n){
if(n===0||n===1){
return 1;
}
return n*factorial(n-1);
}
Here is one I wrote after learning about the array function reduce()
const factorial = n => {
if (! Number.isInteger(n)) return undefined
if (n < 0) return undefined
if (n === 0) return 1
const array1 = [...Array(n+1).keys()].splice(1)
return array1.reduce((preVal, curVal) => preVal * curVal)
}
Just adding a bit in H S Progr's answer as I did today this exercise. In Wikipedia says that 0! = 1 and 1! = 1 , so just an extra " making sure of"
const factorial = (n) => (num === 0 || num === 1) ? 1 : (num * factorial(num - 1));
As I said, I have no merit, as I am learning, but any possible way to ensure that in our if, else if, while ... or any other meaning we choose to do a factorial, we place 0 and 1 with their own unique value.
All merit in my answer ( that was closed to H R Progr, should go to Sonya Moisset who's brilliant article gave me the hints to follow.
This was my original code after reading her article:
const factorial = (n) => (n < 0) ? 1 : (n == 0) ? 1 : (n * factorial(n - 1));
so the below code works this way. the const gets the part of the html doc you want to print to. the prompt receives the number for testing. The fun begins with factorial calculation loop. the loop goes through and continues to multiply the number by its factorial. if you put in 8 the loop would return 40320 after it does all its pass throughs.
const html = document.getElementById('root');
// get number
let num1;
do {
num1 = +prompt("enter number");
}
while (num1 <= 0);
//// factorial calculation using loop
let j = 1;
for (let i = 1; i <= num1; i++) {
j = j * i;
//show results on the screen
html.innerHTML = `
<p> ${j}</p>
`;
}
let myArray = [];
function calculateFactorial (myFacNumber)
{
let result = 1;
let c;
for(let x = 1; x<=myFacNumber; x++)
{
for(let j = x; j<=x;j++)
{
c= myArray[j] = x;
result *= c;
}
}
return result;
}
console.log(calculateFactorial(5));
For future readers, I suggest a non-recursive version of this function.
function factorial(n){
if(n < 0 || !Number.isInteger(n)){
throw Error(`Can't compute factorial(${n}) as factorial is defined for positive integers`);
}
let r = 1;
for(let k=1; k<n+1; k++){
r *= k;
}
return r;
}
Since the function is defined only for positive integers, I have a preference to validate its input to avoid weird errors if n is undefined or not an integer for example.