Apprentice of C (Factorization in C)

Asked

Viewed 273 times

1

Can anyone help me with the logic of this code? the beginning of it I understand but I get a little confused in the part of the for, someone can 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;
}

2 answers

3

Knowing that factorization 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

So:

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 then you can understand 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)

0

It is starting a factorial in 1 and goes up to the n (informed by the user)

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

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

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

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

    return f;
}

Or the one that’s maybe 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);
}
}

Browser other questions tagged

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