Given a quantity N and its reverse R. The duty is to search out the quantity obtained when the quantity is raised to the facility of its personal reverse. The reply will be very massive, return the end result modulo 109+7.
Examples:
Enter : N = 2, R = 2
Output: 4
Rationalization: Quantity 2 raised to the facility of its reverse 2 offers 4 which provides 4 in consequence after performing modulo 109+7Enter : N = 57, R = 75
Output: 262042770
Rationalization: 5775 modulo 109+7 offers us the end result as 262042770
Naive Method:
The best strategy to remedy this drawback may very well be to traverse a loop from 1 to R(reverse) and multiply our reply with N in every iteration.
Observe the steps talked about beneath to implement the concept:
- Create a variable (say ans) and initialize it to 1 to retailer the ultimate end result.
- Then, begin a loop from 1 and it goes until R.
- Multiply the variable ans with N.
- Return the end result ans with modulo of 1e9+7.
Under is the implementation of the above strategy.
C++
|
Time Complexity: O(R)
Auxiliary Area: O(1)
Environment friendly Method: Bit Manipulation
The environment friendly method of fixing this drawback may very well be bit manipulation, simply break the issue into small components and remedy them right here the idea of binary exponentiation methodology might be used.
- Each quantity will be written because the sum of powers of two
- Traverse via all of the bits of a quantity from LSB (Least Important Bit) to MSB (Most Important Bit) in O(log N) time.
Observe the steps talked about beneath to implement the concept:
- First, create a variable (say ans) and initialize it to 1 to retailer the end result.
- Then, test if the given reverse quantity is odd or not.
- If sure, then multiply the reply with pow ans = (ans * pow)%mod.
- Then, multiply the pow with pow i.e., pow = (pow*pow).
- Begin shifting proper by R = R/2.
- Lastly, return the ans as end result.
Under is the implementation of the above strategy
C++
|
Java
|
Time Complexity: O(log N)
Auxiliary Area: O(1)