Cake Number in JavaIn this section, we will learn about finding the cake number in Java. The cake number CK_{n }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, CK_{n }= (n^{3} + 5 *n + 6) / 6 where n >= 0 Thus, For n = 0, CK_{0 }= (0^{3 }+ 5 * 0 + 6) / 6 = (6) / 6 = 6 / 6 = 1 For n = 1, CK_{1 }= (1^{3 }+ 5 * 1 + 6) / 6 = (1 + 5 + 6) / 6 = 12 / 6 = 2 For n = 2, CK_{2 }= (2^{3 }+ 5 * 2 + 6) / 6 = (8 + 10 + 6) / 6 = 24 / 6 = 4 For n = 3, CK_{3 }= (3^{3 }+ 5 * 3 + 6) / 6 = (27 + 15 + 6) / 6 = 48 / 6 = 8 For n = 4, CK_{4 }= (4^{3 }+ 5 * 4 + 6) / 6 = (64 + 20 + 6) / 6 = 90 / 6 = 15 For a = 5, CK_{5 }= (5^{3 }+ 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. CK_{0 }= 1, for n = 0 CK_{1 }= 2, for n = 1 CK_{n} = ^{n + 1}C_{3} + 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 twodimensional 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 abovediscussed approach, there is another approach to compute the cake numbers using combinations. Observe the following mathematical statement. CK_{0 }= 1, for CK_{1 }= 2, for CK_{2 }= 4, for CK_{n} = ^{n}C_{3} + ^{n}C_{2} + ^{n}C_{1} + ^{n}C_{0}, 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
