Algorithm to divide a chocolate bar in equal parts

后端 未结 3 715
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-03 10:14

A random thought popped into my head (when I was sharing a chocolate bar of course!). I was wondering if there is a generic algorithm to solve this problem.

The problem

相关标签:
3条回答
  • 2021-02-03 10:58

    It seems to me that you're looking for numbers that are evenly dividable by all numbers between 1 and n inclusive. That's called the least common multiple of 1, ..., n. A square containing the least common multiple of 1, ..., n squares would by definition be evenly dividable into pieces of size 1, ..., n. You're looking for a maximum of n splits, which adds additional complexity to the problem which may or may not be possible.

    Your example for n = 4 is the LCM(4,3,2,1) which is 12. LCM(5,4,3,2,1) is 60. LCM(6,5,4,3,2,1) is also 60.

    They can always be laid out as 1xLCM(n,...,1) rectangles, and always be dividable into 1,...,n even piles in n-1 or fewer divisions.

    For example, when n = 4, LCM(4,3,2,1) = 12. The rectangle is

    ############
    

    And can be divided as follows:

    1: ############     // 0 cuts
    2: ###### ######    // 1 cut
    3: #### #### ####   // 2 cuts
    4: ### ### ### ###  // 3 cuts (3 being n-1)
    
    0 讨论(0)
  • 2021-02-03 11:02

    Since you can not cut multiple pieces at once, for any number of pieces m you want where m is in the set (1..n), you will always need m-1 cuts. Each cut creates one more piece, you start with one piece.

    Building on the previous solution, I think you were looking intuitively for the following algorithm:

    A = LCM(n)
    p = greatest divisor of A <= sqrt(A)
    q = A/p
    

    The algorithms for this should be trivial, (e.g. start with p = floor(sqrt(A)) and count down until mod(A,p) == 0).

    The reason you want sqrt is to limit the amount of numbers you check. After all, you will always have one divisor <= sqrt(A) and one >= sqrt(A)

    0 讨论(0)
  • 2021-02-03 11:11

    A good way to answer this question would be to use a breadth-first search algorithm. The algorithm would try every possible break of the whole chocolate bar. Then for each of those possible states of the problem, try all possible breaks, and this would continue while keeping track of the evenness of the pieces.

    I'd like to add that the rules would enforce which breaks of the chocolate bar are legal and those possible states which are not legal are thrown out from the algorithm.

    0 讨论(0)
提交回复
热议问题