Write each step of a factorial calculation

Asked

Viewed 7,697 times

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, ex:

3! = 1x2x3 = 6

Follow the code I made. I tried "printar" by decreasing 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);

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

3

What is a bow for? To repeat steps, right?

It is within it that you calculate every factor step, right?

After you finish the steps you are having the final result printed, but you want print out every step!

Did you understand where you have to put the impression? If not, start reading this answer again from the beginning, now with more attention.

Obviously you should format as you wish, choose what should be printed. It may be useful to have an initial impression before starting the steps. And you will still need to print the final result. Run tests.

I could have given the answer ready, but I think you’ll learn better this way.

3

To return the steps of each calculation, concateno em uma string a cada calculo realizado fincando assim:

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

Browser other questions tagged

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