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
Method 1 - Using Mathematics
The solution to this is very simple, if you know mathematics š.
More on wikipedia -Ā http://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence.
The Lazy Caterer’s sequence describes the maximum number of pieces a circle (or a pancake) can be divided into with a given number of straight cuts. The formula to determine the maximum number of pieces from ( n ) cuts is:
$$ P(n) = \frac{n(n + 1)}{2} + 1 $$
Proof
When a circle is cutĀ n
Ā times to produce the maximum number of pieces, represented asĀ f(n)
, each new cut must be considered. The number of pieces before theĀ n
-th cut isĀ f(n-1)
, and the number of pieces added by theĀ n
-th cut isĀ n
.
-
Adding theĀ
n
th cut: To obtain the maximum number of pieces, theĀn
-th cut line should cross all the previous cut lines inside the circle but should not cross any intersections of the previous cut lines. Thus, theĀn
-th line itself intersects the previousĀn-1
Ā lines and is divided intoĀn
Ā segments. -
New number of pieces: Each new segment created by theĀ
n
-th cut divides one existing piece into two parts. Therefore, exactlyĀn
Ā new pieces are added by theĀn
-th cut. -
Recurrence relation: The total number of pieces afterĀ
n
Ā cuts is given by the recurrence relation:f(n) = n + f(n-1)
-
Expanding the recurrence relation: If we repeatedly expand the recurrence relation, we get:
f(n) = n + f(n-1) = n + (n-1) + f(n-2) = n + (n-1) + (n-2) + ... + 1 + f(0)
-
Initial state: When there are no cuts (
n = 0
), there is just one whole piece:f(0) = 1
-
Summation: Combining everything, we get:
f(n) = 1 + (1 + 2 + 3 + ... + n)
-
Arithmetic progression formula: The sum of the firstĀ
n
Ā natural numbers can be given by the formula for the sum of an arithmetic progression:1 + 2 + 3 + ... + n = n(n + 1) / 2
-
Final formula: Substituting this into our expansion:
f(n) = 1 + n(n + 1) / 2
Code
|
|
|
|
Complexity
- ā° Time complexity:Ā
O(1)
as we are using the formula. - š§ŗ Space complexity:Ā
O(1)
as we are using only a few variables.