Tetrahedral Number in JavaIn this section, we will learn what is tetrahedral number and also create Java programs to find tetrahedral numbers. The tetrahedral number program frequently asked in Java coding interviews and academics. Tetrahedron NumberA number is known as a tetrahedral number if the number can be shown like a pyramid with three sides and a triangular base, known as a tetrahedron number. The following diagram shows the same. Mathematical Formula to Find Tetrahedral NumberThe mathematical formula to find the tetrahedral number is mentioned below: Tp = (p * (p + 1) * (p + 2)) / 6, where p >= 1 Let's put the vales in the formula. T1 = (1 * (1 + 1) * (1 + 2)) / 6 = 1 T2 = (2 * (2 + 1) * (2 + 2)) / 6 = 4 T3 = (3 * (3 + 1) * (3 + 2)) / 6 = 10 T4 = (4 * (4 + 1) * (4 + 2)) / 6 = 20 T5 = (5 * (5 + 1) * (5 + 2)) / 6 = 35 Hence, the first five tetrahedral numbers are 1, 4, 10, 20, 35. Tetrahedral Number Java ProgramThe following program uses the mathematical formula to find the tetrahedral numbers. FileName: TetrahedralNumber.java Output: 1 4 10 20 35 56 84 120 165 220 286 364 455 560 680 816 969 1140 1330 1540 1771 2024 2300 2600 2925 3276 3654 4060 4495 4960 Using RecursionUsing recursion also one can find the tetrahedral numbers. The recursive formula to find the tetrahedral numbers are: F(x) = F(x - 1) + (n *(n + 1)) / 2, and F(0) = 0 Let's put the values in the recursively defined formula. F(1) = F(1 - 1) + (1 * (1 + 1)) / 2 = F(0) + 1 = 0 + 1 = 1 F(2) = F(2 - 1) + (2 * (2 + 1)) / 2 = F(1) + 3 = 1 + 3 = 4 F(3) = F(3 - 1) + (3 * (3 + 1)) / 2 = F(2) + 6 = 4 + 6 = 10 F(4) = F(4 - 1) + (4 * (4 + 1)) / 2= F(3) + 10 = 10 + 10 = 20 F(5) = F(5 - 1) + (5 * (5 + 1)) / 2= F(4) + 15 = 20 + 15 = 35 FileName: TetrahedralNumber1.java Output: 1 4 10 20 35 56 84 120 165 220 286 364 455 560 680 816 969 1140 1330 1540 1771 2024 2300 2600 2925 3276 3654 4060 4495 4960 Next TopicCosmic Superclass 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