## Wednesday, June 10, 2015

### Lazy Caterer's sequence

Problem
Given a circular (or regular polygon) cake and a knife by which you can only cut vertically, find the maximum number of pieces of cake you can get by making n cuts. Write a program to do that.

Solution
The solution to this is very simple, if you know mathematics. :P

Number of pieces p
```p = ( n^2+n+2)/2
p = C(n+1,2) + 1
```

More on wikipedia - http://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence.

Proof
When a circle is cut n times to produce the maximum number of pieces, represented as p = Æ’(n), the nth cut must be considered; the number of pieces before the last cut is Æ’(n − 1), while the number of pieces added by the last cut is n.
To obtain the maximum number of pieces, the nth cut line should cross all the other previous cut lines inside the circle, but not cross any intersection of previous cut lines. Thus, the nth line itself is cut in n − 1 places, and into n line segments. Each segment divides one piece of the (n − 1)-cut pancake into 2 parts, adding exactly n to the number of pieces. The new line can't have any more segments since it can only cross each previous line once. A cut line can always cross over all previous cut lines, as rotating the knife at a small angle around a point that is not an existing intersection will, if the angle is small enough, intersect all the previous lines including the last one added.
Thus, the total number of pieces after n cuts is

f(n) = n + f(n-1)
This recurrence relation can be solved. If Æ’(n − 1) is expanded one term the relation becomes
f(n) = n + n-1 + f(n-2)
Expansion of the term Æ’(n − 2) can continue until the last term is reduced to Æ’(0), thus,
f(n) = n + n-1 + n-2 ..... + 1 + f(0)
But f(0) = 1 , because there is one piece before any cuts are made, this can be rewritten as
f(n) = 1 + (1+2+3 + .... n)
This can be simplified, using the formula for the sum of an arithmetic progression:
f(n) = 1+ n*(n+1)/2 = ( n^2+n+2)/2