Given an integer n, denoting the number of cuts that can be made on a pancake, find the maximum number of pieces that can be formed by making n cuts.
Input : n = 1 Output : 2 With 1 cut we can divide the pancake in 2 pieces Input : 2 Output : 4 With 2 cuts we can divide the pancake in 4 pieces Input : 3 Output : 7 We can divide the pancake in 7 parts with 3 cuts Input : 50 Output : 1276
Let f(n) denote the maximum number of pieces that can be obtained by making n cuts. Trivially, f(0) = 1 As there'd be only 1 piece without any cut. Similarly, f(1) = 2 Proceeding in similar fashion we can deduce the recursive nature of the function. The function can be represented recursively as : f(n) = n + f(n-1) Hence a simple solution based on the above formula can run in O(n).
We can optimize above formula.
We now know , f(n) = n + f(n-1) Expanding f(n-1) and so on we have , f(n) = n + n-1 + n-2 + ...... + 1 + f(0) which gives, f(n) = (n*(n+1))/2 + 1
Hence with this optimization, we can answer all the queries in O(1).
Below is the implementation of above idea :
2 4 7 1276
References : oeis.org
This article is contributed by Ashutosh Kumar .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Secretary Problem (A Optimal Stopping Problem)
- Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
- 21 Matchsticks Problem
- Fibonacci problem (Value of Fib(N)*Fib(N) - Fib(N-1) * Fib(N+1))
- Tiling Problem
- 0-1 Knapsack Problem | DP-10
- Perfect Sum Problem
- Transportation Problem | Set 5 ( Unbalanced )
- Transportation Problem | Set 1 (Introduction)
- Cake Distribution Problem
- Josephus Problem Using Bit Magic
- Frobenius coin problem
- Josephus problem | Set 1 (A O(n) Solution)
- N Queen Problem | Backtracking-3
- Transportation Problem Set 8 | Transshipment Model-1
- Number of stopping station problem
- 0/1 Knapsack Problem to print all possible solutions
- The Knight's tour problem | Backtracking-1
- Problem of 8 Neighbours of an element in a 2-D Matrix
- Activity Selection Problem | Greedy Algo-1