How to create a factorial function using the 'for' counter?

Asked

Viewed 116 times

1

Let’s get to the point:

I would like to create a factorial function using the counter for calculating the factor of the parameter numero.

Remembering that 0! = 1 and 1! = 1.

My code is like this:

function fatorial (numero) {
let num = 1;

for (let i = numero; i > numero; i--) {
    num *= num(i);
     }
     return num;
}

The reasoning must be something simple Nothing too gaudy to run away from this my code.

Error message:

expected 1 to Equal 2

I think this factorial reasoning can help:

n! = n(n-1).(n-2)... 3.2.1

  • You’re trying to summon num, which is not a function, but a number.

2 answers

1


Has a syntax problem that makes no sense transforms num function and use there, I know why has that.

In addition, the ending condition of the loop is when it reaches 1 since it does not need to multiply anything else. The way it is will never execute the loop since the condition already starts invalid always, after all the condition checks whether the o is larger than the numero, but just before the code said i is equal to numero then it’s already fake.

function fatorial(numero) {
    let num = 1;
    for (let i = numero; i > 1; i--) {
        num *= i;
    }
    return num;
}
console.log(fatorial(5));

I put in the Github for future reference.

0

I recently made a code similar to this one, in which I wanted to do the decreasing multiplication, but in the end I realized that it was not necessary so I did it in the simplest way:

function fatorial(n) {
    var resultado = 1;
    for (let i = 1; i <= n; i++) {
        resultado *= i;
    }
    return resultado;
}
console.log(fatorial(2));
console.log(fatorial(3));
console.log(fatorial(4));
console.log(fatorial(5));

Note: I start the cycle in 1 because starting at 0 will always result in zero.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.