424,959 Members | 1,136 Online Need help? Post your question and get tips & solutions from a community of 424,959 IT Pros & Developers. It's quick & easy.

Finding maximum value of a data type

 P: 22 I was trying the program to calculate the factorial of a number. The program is to identify the value of number at the which the factorial crosses the range of the data type. How should i do this? Please help me for the logic. I want to accommodate all kinds of data types. Thanks. Oct 1 '15 #1

In C just look in <limits.h>.

In C++ look in <limits>. Learn how to use he numeric_limit class template.

3 Replies

 Expert Mod 5K+ P: 9,197 In C just look in . In C++ look in . Learn how to use he numeric_limit class template. Oct 1 '15 #2

 P: 22 I made the following attempt, but if fails Expand|Select|Wrap|Line Numbers #include #include int main(void) {    int number=0;    unsigned short factorial=1;    printf("Enter the number to calculate factorial\n");    scanf("%d",&number);    printf("us= %d\n",sizeof(unsigned short));    while(number>1)    {        factorial *= number;        if(factorial > USHRT_MAX)        {          break;        }        number -= 1;        printf("%d\n",factorial);    }    return 0; }   And the output looks something like this Expand|Select|Wrap|Line Numbers Enter the number to calculate factorial 9 us= 2 9 72 504 3024 15120 60480 50368 35200 Process returned 0 (0x0)   execution time : 1.874 s Press any key to continue.   After 60480 the value of factorial crosses the range. How to identify this? Oct 2 '15 #3

 Expert Mod 5K+ P: 9,197 This code: Expand|Select|Wrap|Line Numbers while(number>1)    {        factorial *= number;        if(factorial > USHRT_MAX)        {          break;        } etc... doesn't work because factorial has changed before it is tested to see if the max is exceeded. You have to test before factorial is changed. Therefore, check before you multiply. The room left is USHRT_MAX - factorial. Next check to see how many factorial fit in the room by doing (USHRT_MAX - factorial)/factorial. If the number of factorials left is greater than the number you are going to multiply factorial by, then the new amount will fit: Expand|Select|Wrap|Line Numbers     int count = 1;     while(count <= number)    {        if (USHRT_MAX - factorial)/ factorial) > count)        {           factorial *= count;        }        else        {            break;        }               ++count;        printf("%d\n",factorial);    }   Also see that I use the loop counter to do the multiply rather than counting down. Oct 2 '15 #4 