Algorithm to divide a chocolate bar in equal parts

后端 未结 3 783
佛祖请我去吃肉
佛祖请我去吃肉 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 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)

提交回复
热议问题