Skip to content

Grains

Intro

There once was a wise servant who saved the life of a prince. The king promised to pay whatever the servant could dream up. Knowing that the king loved chess, the servant told the king he would like to have grains of wheat. One grain on the first square of a chess board, with the number of grains doubling on each successive square.

There are 64 squares on a chessboard (where square 1 has one grain, square 2 has two grains, and so on).

Task

Calculate the number of grains of wheat on a chessboard given that the number on each square doubles.

Write code that shows:

  • how many grains were on a given square, and
  • the total number of grains on the chessboard

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include "grains.h"
#include <cstdint>
#include <math.h>

namespace grains {
long square(int test) { return pow(2, test - 1); }

unsigned long total() {
unsigned long tmp = 0;
for (std::uint8_t i = 1; i <= 64; i++) {
    tmp += square(i);
}
return tmp;
}

} // namespace grains
1
2
3
4
5
6
7
8
9
#if !defined(GRAINS_H)
#define GRAINS_H

namespace grains {
    long square(int test);
    unsigned long total();
}  // namespace grains

#endif // GRAINS_H

Last update: February 10, 2021

Comments