5. Once upon a time in a kingdom far away, the king hoarded food and the people
ID: 3919283 • Letter: 5
Question
5. 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 help the people, but the king refused. One day a small group of reblo 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 was 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. 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 kis l return grains. Otherwise, make a recursive call, where k is reduced by and grains is doubled. The recursive call computes the total number grains placed in the remaining k - 1 squares. To find the total numbe grains for all k squares, add the result of the recursive call to grainis a return that sum.Explanation / Answer
Since you haven't mentioned any details, I have provided the solution in C++
Feel free to ask me in any other language or any other help
#include<iostream>
using namespace std;
int getTotalGrains(int k,int grains)
{
if(k==1)
return grains;
return getTotalGrains(k-1,grains*2) + grains;
}
int main()
{
int k=3;
cout<<getTotalGrains(k,1);
}
Java solution
import java.io.*;
class GFG {
static int getTotalGrains(int k,int grains){
if(k==1)
return grains;
return getTotalGrains(k-1,grains*2) + grains;
}
public static void main (String[] args) {
int k=3;
System.out.println(getTotalGrains(k,1));
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.