COCONUT AND MONKEY PROBLEM SOLVED THROUGH CODE.

By Victor Gichohi

In 1961 Martin Gardner posed this problem in his “Scientific American” Mathematical Games column and received a record-breaking reader response. Most people could not solve it as the math behind it is very complicated and demanded an answer for it. Twenty years later, he was still receiving emails of people interested in the solution to the puzzle. I tried to solve it using python and I found it quite simple as compared to the mathematical solution. Here’s the puzzle and below is my python code.

Five men and a monkey were shipwrecked on a desert island, and they spent the first day gathering coconuts for food. Piled them all up together and then went to sleep for the night.

But when they were all asleep one man woke up, and he thought there might be a row about dividing the coconuts in the morning, so he decided to take his share. So he divided the coconuts into five piles. He had one coconut left over, and gave it to the monkey, and he hid his pile and put the rest back together.

By and by, the next man woke up and did the same thing. And he had one left over and he gave it to the monkey. And all five of the men did the same thing, one after the other; each one taking the fifth of the coconuts in the pile when he woke up, and each one having one left over for the monkey. And in the morning they divided what coconuts were left, and they came out in five equal shares. Of course each one must have known that there were coconuts missing; but each one was guilty as the others, so they didn’t say anything. How many coconuts were there in the beginning?

def check(pile, verbose=False):
for i in range(0, NUM_ITERATIONS):
share, monkey = divmod(pile, NUM_SAILORS)#get share of each sailor in each iteration and give the monkey the remainder
if monkey == 1:#the monkey must be one
new_pile = pile - (share + monkey)#sets the value for a new pile which is equal to the original pile minus share
if verbose:
print ("%d: share [%d] monkey [%d] new_pile [%d]" % (pile, share, monkey, new_pile))
pile = new_pile
else:
return False
return True

#this function itterates over the possible 0>numbers def solve(upper_bound):
for x in range(1, upper_bound):
if check(x):
return x
return 0

#this if just passes the two methods for possible itteration
if __name__ == "__main__":
x = solve(Uper_Limit)
if x:
print ("Solution: %d" % x)
check(x, True)
else:
print ("No solution < %d" % Uper_Limit)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s