Java Program to Find the Value of a Number Raised to Its Reverse

3 May 2025 | 3 min read

Calculating the value of a number raised to its reverse offers a captivating blend of arithmetic and numerical exploration. This intriguing concept invites curiosity about the interplay between numbers and their reversals, highlighting the beauty of mathematical patterns and relationships.

Problem Statement

We have given a number P and its reverse Q. we have to find the number obtained when the number is raised to the power of its own reverse. You can get very large digits of numbers, so return the result modulo 109+7.

Example 1:

Input: Number = 3, Reverse = 3

Calculation: 3^3=27

Output: 27

Explanation: The number 3 raised to the power of its reverse 3 gives 27, which is the result after performing modulo 10^9 + 7.

Example 2:

Input: Number = 4, Reverse = 4

Calculation: 4^{4} =256

Output: 256

Explanation: The number 444 raised to the power of its reverse 4 gives 256, which is the result after performing modulo 10^9 + 7.

Native Approach

The typical method for determining the power of a number consists of multiplying the base by itself multiple times according to the exponent provided. Although simple to execute and grasp, this method may not be suitable for big exponents because of its linear time complexity. In this approach, we traverse through a loop from 1 to Q (reverse) and multiply our answer with P in each iteration.

Algorithm

  • Define a variable (res) and initialize it to 1 to store the final result.
  • Define a loop from 1 and it goes till Q.
    • Multiply the variable res with P.
  • Return the result res with modulo of 1e9+7.

Let's implement the above algorithm in a Java program.

File Name: PowerCalculator.java

Output:

 125 

Time Complexity: O(exponent)

Auxiliary Space Complexity: O(1)

Using Recursion

It is an efficient way to solve the problem. It is a bit tricky approach. In this approach, we will break the problems in sub-problems and solve them by the concept of exponentiation method. It includes the following steps:

  • We can write every number as the sum of powers of 2.
  • Traverse through all the bits of a number from LSB to MSB in O(log N) time.

File Name: ExponentCalculator.java

Output:

 100000 

Time Complexity: O(exponent)

Auxiliary Space Complexity: O(exponent)