Cake Number in JavaIn this section, we will learn about finding the cake number in Java. The cake number CKn represents the maximum number of pieces a cake can be divided with the help of n planar cuts. The tridimensional version of the pancake numbers is the cake numbers. In general, CKn = (n3 + 5 *n + 6) / 6 where n >= 0 Thus, For n = 0, CK0 = (03 + 5 * 0 + 6) / 6 = (6) / 6 = 6 / 6 = 1 For n = 1, CK1 = (13 + 5 * 1 + 6) / 6 = (1 + 5 + 6) / 6 = 12 / 6 = 2 For n = 2, CK2 = (23 + 5 * 2 + 6) / 6 = (8 + 10 + 6) / 6 = 24 / 6 = 4 For n = 3, CK3 = (33 + 5 * 3 + 6) / 6 = (27 + 15 + 6) / 6 = 48 / 6 = 8 For n = 4, CK4 = (43 + 5 * 4 + 6) / 6 = (64 + 20 + 6) / 6 = 90 / 6 = 15 For a = 5, CK5 = (53 + 5 * 5 + 6) / 6 = (125 + 25 + 6) / 6 = 156 / 6 = 26 ImplementationLet's see how one can implement the above mathematical formula. Observe the following example. FileName: CakeNumberExample1.java Output: The first 30 cake numbers are: 1 2 4 8 15 26 42 64 93 130 176 232 299 378 470 576 697 834 988 1160 1351 1562 1794 2048 2325 2626 2952 3304 3683 4090 Using RecursionThe cake numbers can also be found using recursion. However, to find cake numbers using recursion, we must know the recursive formula of it. CK0 = 1, for n = 0 CK1 = 2, for n = 1 CKn = n + 1C3 + n + 1, for n >= 2 Thus, For n = 2 ImplementationLet's see how one can implement the above mathematical formula. Observe the following example. FileName: CakeNumberExample2.java Output: The first 30 cake numbers are: 1 2 4 8 15 26 42 64 93 130 176 232 299 378 470 576 697 834 988 1160 1351 1562 1794 2048 2325 2626 2952 3304 3683 4090 Using IterationThe cake numbers can also be found using iteration. We will use loops to find the cake numbers with the help of a two-dimensional array. Observe the following program. FileName: CakeNumberExample3.java Output: The first 30 cake numbers are: 1 2 4 8 15 26 42 64 93 130 176 232 299 378 470 576 697 834 988 1160 1351 1562 1794 2048 2325 2626 2952 3304 3683 4090 Another ApproachApart from the above-discussed approach, there is another approach to compute the cake numbers using combinations. Observe the following mathematical statement. CK0 = 1, for CK1 = 2, for CK2 = 4, for CKn = nC3 + nC2 + nC1 + nC0, for n >= 3 Thus, For n = 3, ImplementationLet's see the recursive as well as the iterative implementation of the above formula to find the cake numbers in the code mentioned below. FileName: CakeNumberExample4.java Output: The first 30 cake numbers are: 1 2 4 8 15 26 42 64 93 130 176 232 299 378 470 576 697 834 988 1160 1351 1562 1794 2048 2325 2626 2952 3304 3683 4090 The first 30 cake numbers are: 1 2 4 8 15 26 42 64 93 130 176 232 299 378 470 576 697 834 988 1160 1351 1562 1794 2048 2325 2626 2952 3304 3683 4090 Next TopicCompare time in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India