Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can C print a super-large number?

How can this code print such a large number? I have tried it on Ubuntu 14.04 (gcc 4.8.2). It does not work the same on MS Windows with any compiler (even MinGW, which is called "gcc for Windows"). Why?

#include <stdio.h>
#include <math.h>
int main()
{
    printf("%.0f\n",pow(2,500));
}

Ubuntu output:

3273390607896141870013189696827599152216642046043064789483291368096133796404
674554883270092325904157150886684127560071009217256545885393053328527589376

Windows output:

3273390607896141900000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000

(The line break is added for clarity only.)

like image 661
adarsh Avatar asked Dec 20 '22 07:12

adarsh


1 Answers

As hinted by OP and commented by @user300234, 2^500 is a 501 bit number, but that is not the issue here.

pow(2,500) returns a double, about 3.27e150, which is typically a binary64. This type supports about 15 - 17 decimal digits of precision. So for numbers near 3.27e150, printing more that 17 digits of significance is usually not important. It is well smaller than DBL_MAX which may be about 1.798e308.

The trick here is that pow(2,500) is exactly representable as a floating point double (binary64). This may give the illusion that a double has hundreds of bits of precision - it does not.

The 2 different compilations handle conversion of double to text in different ways, once 17 or so digits are printed - this is allowable by the C spec. The minimum number of correct digits is DBL_DECIMAL_DIG - likely 17 on both systems.

Consider printing the next greater double. Although the next double could be printed with 150 or so digits, typically these additional digits way pass DBL_DECIMAL_DIG are simply noise for many applications.

// 2 ^ 500
327339060789614 187001318969682759915221664...
// next
327339060789614 259685191399243448970154045...
like image 145
chux - Reinstate Monica Avatar answered Dec 29 '22 16:12

chux - Reinstate Monica