Skip to content
Advertisement

how to find 2 to the power of n . n ranges from 0 to 200

Assume my system as 32 bit machine. Considering this if I use long int for n>63 I will get my value as 0. How to solve it?

Advertisement

Answer

double is perfectly capable of storing powers of two up to 1023 exactly. Don’t let someone tell you that floating point numbers are somehow always inexact. This is a special case where they aren’t!

double x = 1.0;
for (int n = 0; n <= 200; ++n)
{
    printf("2^%d = %.0fn", n, x);
    x *= 2.0;
}

Some output of the program:

2^0 = 1
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
...
2^196 = 100433627766186892221372630771322662657637687111424552206336
2^197 = 200867255532373784442745261542645325315275374222849104412672
2^198 = 401734511064747568885490523085290650630550748445698208825344
2^199 = 803469022129495137770981046170581301261101496891396417650688
2^200 = 1606938044258990275541962092341162602522202993782792835301376
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement