C - how to calculate the factorial of a number?

Asked

Viewed 33,840 times

-1

I’m trying but I’m not getting it, for example: factor 5 is given by 5 * 4 * 3 * 2 * 1.

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

  • 1

    Share what you’ve tried in code form

3 answers

3


You take the value that will serve as reference in the case I am using the N
Right after we create a FOR where it will repeat itself until the N be equal to 1, making inside the body of FOR the calculation of Factorial

  scanf("%d", &n) ;

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

Staying since way 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;
}
  • Do you mind explaining what’s going on in there? As this does not seem to help the AP much - he did not understand how to do, and then has a program ready with "do it this way". Maybe I could be more didactic.

2

Follows a function (using while) quite simple 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 use a bow tie for:

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 kind of loop is by using a pre-calculated table containing all the 21 possible results that fit within a unsigned long long:

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];
}

1

Another alternative is to use a call recursive, this is 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);
    }
}
  • 1

    Ready @Miguel changed code

  • 1

    The body of his fatorial(int) can be simplified to: return n < 2 ? 1 : n * fatorial(n - 1);. Another, why are you returning double?

  • Yes, that was just an example.

  • @Márioferoldi, to return double really doesn’t make sense the way you’re willing.

Browser other questions tagged

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