-5

I needed some help with a problem I'd been assigned in class. It's our introduction to for loops. Here is the problem:

Consider the following riddle.

After a plane crash 3 people are stranded on a desert island. They spend the first day gathering a pile of bananas. They decide to count them the next morning and split them up between each equally.

In the middle of the night each person decides they can't trust their fellow shipmates. So, each in turn, gets up and divides the pile into 3 equal sections and conceals their share. However, when dividing it there was a single banana left over, which they gave to a nearby bear. When morning comes, the group divides the remaining pile into 3 equal piles and one banana is left over, which they give to a nearby bear.

What is the SMALLEST pile which solves the riddle?

Write a set of for-loops which can solve this riddle for ANY number of people and ANY number of bears.

I'm really unsure how to pursue this problem. I think it should involve two for loops (one within another?).

This is all I have so far:

function pile = IslandBananas(numpeople, numbears)
for pilesize=1:10000000
ultimatepile=(1/3)*((2/3)*(pile-1)-1) = 1;
end
for pile>1
ultimatepile=pile-1
end

I'm not really sure how correct this is, so I would really appreciate your input.

4

1 回答 1

0

我现在无法访问 MATLAB,但我认为您只需要这个:

p = input('Enter the number of people: ');
while(ceil(p) ~= floor(p))    %    `p` has to be an integer value.
    p = input('Nice try. Enter the number of people: ');
end
b = input('Enter the number of bears: ');
while(ceil(p) ~= floor(p))    &    `b` has to be an integer value.
    p = input('Nice try. Enter the number of bears: ');
end

for min_share = 1:Inf
    S = min_share*p + b;    %    `S` will hold the size of the pile.

    for ii = 1:p
        if(ceil(S) ~= floor(S))    %    The pile must have an integer size at the end of every itereation.
            break;
        end
        S = (S/2)*p + b;
    end

    if(ceil(S) == floor(S))    %    If the size of the current pile is an integer, we have found our answer.
        break;
    end
end
于 2013-07-25T04:02:54.413 回答