In ancient times, a wise person presented a challenge to a curious king: place 1 grain of rice on the first square of a chessboard, and for each subsequent square, double the number of grains.
For example:
- 1st square → 1 grain
- 2nd square → 2 grains
- 3rd square → 4 grains
- 4th square → 8 grains
- 5th square → 16 grains
- And so on... continuing this pattern across all 64 squares of the chessboard.
The king agreed, but as the rice doubled on each square, he quickly realized the scale of the task. By the time the rice reached the last square, it would exceed all the resources in his kingdom.
Write a JavaScript function calcSquaresNeeded(grains)
that takes a number of grains and returns up to which square of the chessboard one should count in order to get at least as many grains.
Examples:
calcSquaresNeeded(0); // Should return 0
calcSquaresNeeded(1); // Should return 1
calcSquaresNeeded(2); // Should return 2
calcSquaresNeeded(3); // Should return 2
calcSquaresNeeded(7); // Should return 3
calcSquaresNeeded(10); // Should return 4
Constraints:
- The number of grains will always be a positive integer.