Apprentice C (C-Factor)

1

Someone can help me in the logic of this code? the beginning of it I understand but I get a bit cluttered in the part of the, can someone help me to understand?

#include <stdio.h>

int main(){

int fatorial, n;
printf("insira o numero que vc quer fatorar\n");
scanf("%i",&n);

for(fatorial=1;n>=1; n--){
    fatorial *= n;

}
printf("o fator do seu numero e: %i",fatorial);
return 0;
}
    
asked by anonymous 14.12.2018 / 19:55

2 answers

3

Knowing that factoring is the multiplication of a number by all its positive numbers smaller than it. For example: Factorial of 5 = 5 x 4 x 3 x 2 x 1 = > 120

Then:

At each iteration in the loop, the chosen number (n) is multiplied by its predecessor (n-1)

for(fatorial=1;n>=1; n--){
    fatorial = fatorial * n;

}

Maybe you can understand it a little better.

iteração 1: fatorial = 1 * 5; (fatorial vale 5)
iteração 2: fatorial = 5 * 4; (fatorial vale 20)
iteração 3: fatorial = 20 * 3; (fatorial vale 60)
iteração 4: fatorial = 60 * 2; (fatorial vale 120)
iteração 5: fatorial = 120 * 1; (fatorial vale 120)
    
14.12.2018 / 20:06
0

He is starting a factorial at 1 and goes to n (user informed)

And with each interaction it will multiply the factorial (start = 1) by n , *= does the same as fatorial = fatorial * n

There are other ways to calculate the factorial, for example by using this very simple with a while loop.

unsigned long long fatorial( int n )
{
    unsigned long long f = 1;

    while( n > 0 )
        f *= n--;

    return f;
}

Or maybe it's a little more complicated to understand because it's recursive.

long long fatorial(int n){
long long fat;
if ( n <= 1 )
    return (1);
else{
   return n * fatorial(n - 1);
}
}
    
14.12.2018 / 20:05