There is a story of the inventor of chess. The king wanted to reward him with ri
ID: 669458 • Letter: T
Question
There is a story of the inventor of chess. The king wanted to reward him with riches, but he only asked for the following. One grain of wheat for the first square, two on the second, four on the third, doubling the amount for each squre until 64 squares are accounted for.
a) Design a program in C++ for calculating the total number of grains of wheat. You will want to use iteration/looping. Do not forget to keep track of which square you are on and the number of grains of wheat that you currently have.
b) Write the program to determine the number of squares needed to get at least X grains of wheat.
Hints: You will need to keep track of the number of grains of wheat on the current square, the square you are on, and the total number of grains on all previous squares. It is helpful to print out the values of all variables each time through a loop for tracking and debugging.
c) How many squares are needed for 1000, 1,000,000 and 1,000,000,000 grains of wheat.
Sample output: Number of squares required for 1000 is 10
d) What is the largest number of squares you can calculate the exact number of grains using an int?
e) What is the largest number of squares you can calculate the approximate number of grains using a double?
Explanation / Answer
a) #include <iostream>
#include <cmath>
using namespace std;
int main() {
int calc = 1;
int sqNum = 1;
unsigned long long total = 1;
cout << "Square " << sqNum << " has " << total << " grain of wheat" << endl;
for (int i = 1; i<64; ++i){
sqNum++;
calc = (calc * 2);
total = total + calc;
cout << "Square " << sqNum << " has " << total << " grains of wheat " << endl;
}
return 0;
}
________________________________________________________________
#include <iostream>
using namespace std;
int main( ) {
int squares;
int grains;
for (squares = 1, grains = 1; squares <= 20; ++squares) {
grains *=2;
cout << "Squares: " << squares << " and grains: " << grains << endl;
}
return 0;
}
______________________________________________________________________________
#include "../std_lib_facilities.h"
int grain_count();
void print_count(int count_grains);
int main()
{
int count_grains = 0;
count_grains = grain_count();
print_count(count_grains);
keep_window_open();
}
int grain_count()
{
int no_of_squares = 0;
int current_square = 0;
int no_of_current_sq_grains = 0;
int previous_square_grains = 0;
for (int i = 0; i < 64; i += 2)
{
no_of_squares = i;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.