简体   繁体   中英

Python “Wheat and Chessboard legend”

There is an old "Wheat and chessboard" problem: If a chessboard were to have wheat placed upon each square such that one grain were placed on the first square, two on the second, four on the third, and so on (doubling the number of grains on each subsequent square).

grains = 1
for square in range(1, 64+1):
print(square, grains)
grains *= 2
  • This will give the complete range of the "chessboard" with the number of grains.

How can i program it that the user will type in a specific square number and get the correct number of grains for each specific tile? Exp: input = 5 the answer is 16 and so on I need to use the range-Function. if possible.

Thank you!!!

The number of grains on a tile = 2^nrTile . So ask input and return 2^input .

Let the user input the square number in a variable square

Then we can do:

grains = 2 ** (square - 1)
print(grains)

Basically, you'll observe that each square has 2^(n-1) grains in it. So this way it simplifies the problem.

(Assuming the squares start from 1, not 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM