Compute the total number of grains of wheat that were placed on k squares by writing a recursive method getTotalGrains(k, grains). Each time getTotalGrains is called, it “places” grains on a single square; grains is the number of grains of wheat to place on that square. If k is 1, return grains. Otherwise, make a recursive call, where k is reduced by 1 and grains is doubled. The recursive call computes the total number of grains placed in the remaining k - 1 squares. To find the total number of grains for all k squares, add the result of the recursive call to grains and return that sum.

Once upon a time in a kingdom far away, the king hoarded food and the people starved. His adviser recommended that the food stores be used to help the people, but the king refused. One day a small group of rebels attempted to kill the king, but were stopped by the adviser. As a reward, the adviser was granted a gift by the king. The adviser asked for a few grains of wheat from the king’s stores to be distributed to the people. The number of grains were to be determined by placing them on a chessboard. On the first square of the chessboard, he placed one grain of wheat. He then placed two grains on the second square, four grains on the third square, eight grains on the fourth square, and so forth.

This demonstrates a recursion where a partial solution is being built up on the way down the recursion. What makes this interesting is that it is not just a tail recursion (the partial solution becomes the complete solution at the bottom of the recursive chain), but that it computes an answer using each of the partial solutions.


See the code in Grain.java.

Computer Science & Information Technology

You might also like to view...

Use the motion tweening techniques covered in this chapter to create an exploding text effect. Place a button in the movie, which when pressed, starts a spark traveling down a fuse to a string of text. When the spark reaches the text, make the text explode off the screen.

What will be an ideal response?

Computer Science & Information Technology

Text for a SmartArt graphic must only be entered within the Text Pane

Indicate whether the statement is true or false

Computer Science & Information Technology

________ is the use of the Internet, smartphones, or other devices to send or post content intended to hurt or embarrass another person.

A. Identity theft B. Trojan horse attack C. Zombie apocalypse D. Cyberbullying

Computer Science & Information Technology

Circularly linked lists are primarily used in lists that allow access to nodes in the middle of the list without starting at the beginning.

Answer the following statement true (T) or false (F)

Computer Science & Information Technology