-3

I'm doing my homework and i need to do a program .i need to do a factorial n>12 and i do everything but i haven't solution.

My problem appear because I use unsigned long long and it's only have 32bytes. but 13! have more number than this . I need to use long double but i don't know how to use it .

#include <stdio.h>
#include <stdlib.h>
unsigned long long factorial(int x) 
(13!>2^32-1)--> max 32 bytes
   {int i=1;
    int aux=1;
    int p;
    p= x+1;
        while (i<p)
        {
        aux*=i;
        i++;
        }
     x=aux;
   };
int main()
{
    float v1=0;
    int e1=0;
    while(e1<1 || e1>12)
        {printf("Ingrese un valor: ");
        scanf("%f",&v1);
        e1=v1/1;/
        if(e1!=v1)
            printf("Solo se considera el numero entero: %d \n",e1);
        if(e1>12)
            printf("Este programa solo calcula hasta 12! (12 factorial) \n\n");}
    printf("El factorial de %d es: %d \n",e1,factorial(e1));
    printf("%d! = %d \n",e1,factorial(e1)); 
    return 0;
}
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
pepitox20
  • 11
  • 2
  • 2
    Use `unsigned long long` **for every variable**. And adjust your printf's (and scanf's)!! – pmg Apr 22 '19 at 15:43
  • Hint: `uint64_t`. Also, why `float`? And this looks wrong: `e1=v1/1;/`. And turn your compiler warnings *up* and fix all warnings. – Jesper Juhl Apr 22 '19 at 15:43
  • 1
    Possible duplicate of [Calculate the factorial of an arbitrarily large number, showing all the digits](https://stackoverflow.com/questions/1966077/calculate-the-factorial-of-an-arbitrarily-large-number-showing-all-the-digits) – Mark Benningfield Apr 22 '19 at 15:43

1 Answers1

0

You must

  • work with unsigned long long instead of int
  • return the value from the function instead of writing to its argument
  • use the %llu format specifier in printf instead of %d

Like this:

#include <stdio.h>

unsigned long long factorial(int x)
{
    unsigned long long aux = 1;
    while(x > 1) {
        aux *= x;
        x--;
    }
    return aux;
}

int main(void)
{
    for(int i = 0; i <= 20; i++) {
        printf("%d! = %llu\n", i, factorial(i));
    }
    return 0;
}

Program output:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
11! = 39916800
12! = 479001600
13! = 6227020800
14! = 87178291200
15! = 1307674368000
16! = 20922789888000
17! = 355687428096000
18! = 6402373705728000
19! = 121645100408832000
20! = 2432902008176640000

But a 64-bit integer cannot handle 21! or greater.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56