C - how to calculate the factorial of a number? [duplicate]

0

To try but I can not, for example: the factorial of 5 is given by 5 * 4 * 3 * 2 * 1.

You have to develop a program that calculates the factorial of a given number as input. (using for)

    
asked by anonymous 26.01.2018 / 18:33

3 answers

1

You get the Value that will serve as a reference in case I am using N
 Soon after we'll create a FOR where it will repeat itself until the N is equal to 1 , doing it inside the FOR < strong> Factorial calculation

  scanf("%d", &n) ;

  for(fat = 1; n > 1; n = n - 1)
  {      
      fat = fat * n;
  }

Getting it right at the end:

#include<stdio.h>

int fat, n;

int main()
{
  scanf("%d", &n) ;

  for(fat = 1; n > 1; n = n - 1)
  {
      fat = fat * n;
  }

  printf("\n%d", fat);
  return 0;
}
    
26.01.2018 / 18:36
1

Here is a fairly simple function (using while ) able to calculate factorial of a number n :

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

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

    return f;
}

If the idea is to even use a for loop:

unsigned long long fatorial( int n )
{
    unsigned long long f = 1;
    for( ; n > 0; f *= n-- );
    return f;
}

Another way to solve the problem without any type of loop is to use a pre-calculated table containing all% of possible results that fall within a 21 :

unsigned long long fatorial( int n )
{
    static const unsigned long long fat[21] = { 1ULL, 1ULL, 2ULL, 6ULL, 24ULL, 120ULL, 720ULL, 5040ULL,
                                                40320ULL, 362880ULL, 3628800ULL, 39916800ULL, 479001600ULL,
                                                6227020800ULL, 87178291200ULL, 1307674368000ULL,
                                                20922789888000ULL, 355687428096000ULL, 6402373705728000ULL,
                                                121645100408832000ULL, 2432902008176640000ULL };
    return fat[n];
}
    
26.01.2018 / 19:33
1

Another alternative is to use a recursive call, here's the example:

#include <stdio.h>

double fatorial(int n);
int main(void){
    int num = 3;
    printf("Fatorial de %d = %.0lf",num,fatorial(num));
    return 0;
}

double fatorial(int n){
    double fat;
    if ( n <= 1 )
        return (1);
    else{
       return n * fatorial(n - 1);
    }
}
    
26.01.2018 / 18:52