Hyperfactorial in JavaHyperfactorial of a number is the outcome of multiplying a given number of continuous numbers from 1 to that number, where each number is raised to its power. Mathematically, Thus, H(1) = 1 ^ 1 = 1 H(2) = 1 ^ 1 × 2 ^ 2 = 1 × 4 = 4 H(3) = 1 ^ 1 × 2 ^ 2 × 3 ^ 3 = 1 × 4 × 27 = 108 H(4) = 1 ^ 1 × 2 ^ 2 × 3 ^ 3 × 4 ^ 4 = 1 × 4 × 27 × 256 = 27648 H(5) = 1 ^ 1 × 2 ^ 2 × 3 ^ 3 × 4 ^ 4 × 5 ^ 5 = 1 × 4 × 27 × 256 × 3125 = 86400000 Java Program to Find the Hyperfactorial NumberThe following program uses the mathematical formula to find the Hyperfactorial numbers. FileName: HyperFactorialNumber.java Output: The first 5 HyperFactorial numbers are: 1 4 108 27648 86400000 To find each hyperfactorial number, the above program is taking O(n ^ 2) time. We can do the optimization to reduce the time complexity. Consider the following program. FileName: HyperFactorialNumber1.java Output: The first 5 HyperFactorial numbers are: 1 4 108 27648 86400000 The findPow() method has the time complexity of O(log(n)), and this method has been called by a for-loop that runs with the time complexity of O(n). Thus, the total time complexity is O(nlog(n)), which is better than the previous code. Finding Hyperfactorial Number Using RecursionUsing recursion also, one can find the HyperFactorial numbers. The recursive formula to find the hyperfactorial number is: H(1) = 1 H(p) = H(p - 1) × p ^ p, where p >= 2 Thus, H(2) = H(2 - 1) × 2 ^ 2 = H(1) × 4 = 1 × 4 = 4 H(3) = H(3 - 1) × 3 ^ 3 = H(2) × 27 = 4 × 27 = 108 H(4) = H(4 - 1) × 4 ^ 4 = H(3) × 256 = 108 × 256 = 27648 H(5) = H(5 - 1) × 5 ^ 5 = H(4) × 15625 = 27648 × 15625 = 86400000 Let's translate the above recursive formula into the Java code. FileName: HyperFactorialNumber2.java Output: The first 5 HyperFactorial numbers are: 1 4 108 27648 86400000 Next TopicIdentifier Expected Error 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