Write each step of calculating a factorial

1

I have a piece of code that calculates the factorial of a number in JavaScript, but I wanted it to return the steps of each calculation, eg:

  

3! = 1x2x3 = 6

Follow the code I made. I tried to "print" decrementing the variable, but I'm not sure what I'm doing.

var fatorial=1;
var num=parseInt(prompt("Digite um número: "));

for(var x=1; x<=num; x++)
{
  fatorial=fatorial*x;
}

document.write(num+"! = "+num+"x"+(num--)+"="+fatorial);
    
asked by anonymous 31.05.2018 / 06:10

2 answers

3

What is a loop for? For repeat steps , right?

It's within it that you calculate each step of the factorial, right?

After finishing the steps you are going to print the final result, but you want to print each step !

Have you understood where to put the print? If not, start reading this response again from the beginning, now with more attention.

Obviously you should format as you wish, choosing what to print. It may be helpful to have an initial impression before beginning the steps. And you still need the impression of the end result. Take tests.

I could have given the answer ready, but I think it will learn better.

    
31.05.2018 / 06:21
3

To return the steps of each calculation, I concatenate in a string every calculation performed by doing this:

var fatorial=1;
var explicaFator = '';
var num=parseInt(prompt("Digite um número: "));
for(var x=1; x<=num; x++)
{
    fatorial=fatorial*x;
    if(explicaFator != ''){
      explicaFator += 'x';
    }
    explicaFator += x;
    
}
document.write(num+"! = "+explicaFator+" = "+fatorial);
    
31.05.2018 / 06:23