Calculations Factorial involve Very Large Numbers, and this should be taken into account because in practice the available memory is always finite.
More robust codes are able to filter inputs that produce "incalculable" outputs due to machine memory limitations.
Taking your reasoning into consideration, we can implement a function for factorial calculation capable of returning an error if the entry is invalid or incalculable, for example: n < 0
or n > 20
.
The largest number capable of being stored in a type variable unsigned long long
is 18.446.744.073.709.551.615
.
The factorial of 20
can be perfectly stored in a unsigned long long
for:
20! = 2.432.902.008.176.640.000 < 18.446.744.073.709.551.615
The factorial of 21
extrapolates the storage capacity of a unsigned long long
for:
21! = 51.090.942.171.709.440.000 > 18.446.744.073.709.551.615
Taking your reasoning into consideration, follow an example:
#include <stdio.h>
#include <stdlib.h>
int fatorial( int n, unsigned long long * f )
{
/* Verifica se o calculo eh possivel*/
if( n < 0 || n > 20 )
{
return -1; /* retorna -1 em caso de erro */
}
*f = 1;
while( n > 0 )
{
(*f) *= n;
n--;
}
return 0; /* retorna 0 em caso de sucesso */
}
int main( int argc, char ** argv )
{
int num = atoi(argv[1]);
int ret = 0;
unsigned long long fat = 0;
ret = fatorial( num, &fat );
if( ret < 0 )
{
printf( "Erro!\n" );
return 1;
}
printf("%d! = %llu\n", num, fat );
return 0;
}
Exits:
$ ./fatorial 5
5! = 120
$ ./fatorial 10
10! = 3628800
$ ./fatorial 15
15! = 1307674368000
$ ./fatorial 20
20! = 2432902008176640000
$ ./fatorial 21
Erro!
$ ./fatorial -1
Erro!