Reputation: 169
Suppose i want to store 2^100 in a variable. No integer type allows this. But this can be stored in a double variable with zeros after the decimal point i.e the following code may be used.
double no = 1;
int i = 1;
for(i=1;i<=100;i++) no*=2;
I now want to print 'no' without what is there after decimal point. Can this be done. I'm just interested in printing and not its storage.
Note: I know the problem can be done using array of integer,so please don't suggest that method.
Upvotes: 3
Views: 2729
Reputation: 11209
You are talking about arbitrary precision integers for which I would advice to use a library such as GMP. See https://gmplib.org.
Using floating point numbers will not solve your problem because it will round your integer to the closest floating point number and you will lose precision.
"On a typical computer system, a 'double precision' (64-bit) binary floating-point number has a coefficient of 53 bits (one of which is implied), an exponent of 11 bits, and one sign bit." (Wikipedia)
As long as we only deal with powers of 2 then the floating point representation is exact: One significant digit (1) and an exponent equal to 100. So you can get away with using a double. Once you add any number small enough in comparison with the stored number, you are left with the original number as a result. Classic floating point issues.
Upvotes: 4
Reputation: 129314
Something like:
std::cout << std::fixed << std::setprecision(0) << no << std::endl;
Complete program:
#include <iostream>
#include <iomanip>
int main()
{
double no = 1;
int i = 1;
for(i=1;i<=100;i++) no*=2;
std::cout << std::fixed << std::setprecision(0) << no << std::endl;
}
Prints:
1267650600228229401496703205376
(Which is exactly 2^100, but if you do no + 1.0
in the above code, it prints exactly the same value, since adding one is outside of the covered precision of the value.
Upvotes: 1
Reputation: 28837
You will need to use an array to simulate it. It is a good problem to solve as it's is useful for other Euler problems.
Upvotes: 0
Reputation: 126110
You say C++, but this is much easier to do with C I/O (which you can use in C++, but its not really C++). You just want to print in f
format with no digits after the decimal:
printf("%.0f\n", no);
In C++ you can do the same with:
std::cout << std::fixed << std::setprecision(0) << no << std::endl;
which is much more verbose, and has persistent effects on later things printed...
Upvotes: 1