Factorial algorithm in Portugol Studio

I have this algorithm:

programa 
{
    inteiro numero, fatorial, resultado=1

    funcao inicio() 
    {
        escreva ("Insira um número a ser fatorado: ")
        leia (numero)

        para (fatorial = 1; fatorial <= numero; fatorial++)
        {
            resultado = resultado * fatorial
        }

        escreva ("O fatorial de ", numero, " é: ", resultado)
    }
}

Which correctly returns the factorial to me. But how do I get him to return all the math?

EX.:

5! = 5x4x3x2x1=120

Author: LINQ, 2017-04-11

2 answers

The first thing you need to keep in mind is that the loop (para) it needs to be the other way around. This is because it will become easier to concatenate the multiplications in a string (variable of type cadeia).

For example, the factorial of 3 has Result 6 the representation would be 3! = 3x2x1 = 6 . Notice that it is much easier to concatenate the text if the multiplication starts with 3.

Keeping this in mind, follows the algorithm

inteiro numero, fatorial, resultado = 1
cadeia texto = "" //Variavel para salvar a representação final (3x2x1)

escreva ("Insira um número a ser fatorado: ")
leia (numero)

/* Perceba que aqui o loop (para), corre de trás pra frente. Ou seja, ele começa no número
 * que foi digitado pelo usuário (fatorial = numero), acontece enquanto o multiplicador 
 * for maior ou igual a 1 (fatorial >= 1) e vai diminuindo 1 do multiplicador 
 * a cada passada (fatorial--) */

para (fatorial = numero; fatorial >= 1; fatorial--)
{
    // Aqui, se for 1 não precisamos concatenar o sinal de multiplicação (x)
    se(fatorial == 1){
        texto = texto + fatorial
    }senao{
        texto = texto + fatorial + "x"
    }

    resultado = resultado * fatorial
}

escreva (numero, "! = ", texto, " = ", resultado)
 1
Author: LINQ, 2017-04-12 12:02:14
texto t = ""
para (fatorial = numero; fatorial >= 1; fatorial--) //Realiza o decremento
{
    if(fatorial != 1){ //Verifica se diferente de 1 para não adicionar o "x"
       t = t + fatorial + "x"
    } else {
       t = t+ fatorial
    }
    resultado = resultado * fatorial
}
escreva (fatorial, "! = ",t , " = ", resultado)

/ / I haven't seen portugol

 0
Author: Deividson Oliveira, 2017-04-13 20:20:51