// G. Hagopian--PPP4-exercise9
/*
9. Try to calculate the number of rice grains that the inventor asked for in
exercise 8 above. You’ll find that the number is so large that it won’t fit
in an int or a double. Observe what happens when the number gets too large
to represent exactly as an int and as a double. What is the largest number
of squares for which you can calculate the exact number of grains (using
an int)? What is the largest number of squares for which you can calculate
the approximate number of grains (using a double)?
*/
#include
using namespace std;
unsigned int sumOfPow2(unsigned int n) {
unsigned int accumulator{};
unsigned int pow2 = 1;
for (unsigned int i = 0; i < n; ++i) {
accumulator += pow2;
pow2 *= 2;
}
return accumulator;
}
double sumOfPow2(double n) {
double accumulator{};
double pow2 = 1;
for (double i = 0; i < n; ++i) {
accumulator += pow2;
pow2 *= 2;
}
return accumulator;
}
int main() {
unsigned int squares{};
double dsquares{};
cout << "How many squares are there? ";
cin >> squares;
for (unsigned int i = 0; i < squares; ++i) {
cout << "sumOfPow2(" << i << ") = " << sumOfPow2(i) << endl;
}
dsquares = squares;
for (double i = 0; i < dsquares; ++i) {
cout << "sumOfPow2(" << i << ") = " << sumOfPow2(i) << endl;
}
}