Buy three get one (a foreign company interview question)

Source: Internet
Author: User

Problem Description:

28 soldiers went to buy water, 3 empty bottles can be replaced by a bottle of water, ask the most to buy a few bottles of water can make all the soldiers drink water, and do not waste.

Problem Analysis:

The key to this problem is that 3 empty bottles of water will also produce empty bottles, and the first time to buy water bottles is not necessarily a 3 multiples. To understand this, the problem is solved.

If you purchase n bottles of water, then set F (n) as the number of bottles that can be given water, then:

F (n) = (N/3) + ((N/3) + (n%3)/3 + (((N/3) + (n%3)/3 + ((N/3) + (n%3)%3)/3 + ...

So the water we've actually obtained recently has n + f (n) bottles.

The code is as follows (Python implementation):

# Calculate How many extral bottles is free if you buy "num" bottles
def extrabottle (num):
    n = int (num)
    r = 0  While N/3! =
    0:
        # Calc Free bottle
        r = r + N/3
        # Calc Empty bottle number 
        # (empty ones of free bottle + empty ones of remainder)
        n = n/3 + n%3
    return r

def bottletobuy (num):
    i = Int (1) while
    TRUE:
 if (i + extrabottle (i) >= num):
           break
        i + = 1
    return i

print bottletobuy (28)


Last Answer: 19

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.