Skip to content

Instantly share code, notes, and snippets.

@luisjunco
Last active February 16, 2025 19:45
Show Gist options
  • Save luisjunco/dcec6ca49602eaf7b023947505fea6c6 to your computer and use it in GitHub Desktop.
Save luisjunco/dcec6ca49602eaf7b023947505fea6c6 to your computer and use it in GitHub Desktop.
JavaScript Interview - The rice and chessboard problem

JavaScript Interview - The rice and chessboard problem


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.


Your task

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment