Given integer N and values P and Q, The duty is to calculate the minimal variety of powers of P and Q required to generate N.
Observe: The 0th energy of the values can be thought-about.
Examples:
Enter: N = 15, P = 2, Q = 3
Output: 3
Clarification: We will make 15 through the use of (8, 4, 3) or (9, 3, 3). Each take 3 numbers.Enter: N = 19, P = 4, Q = 3
Output: 2
Clarification: Within the second case, we are able to make 19 through the use of (16, 3) which is 2 numbers.
Strategy: Recursion (Memoization)
The Fundamental concept is to make use of memoization strategy for this drawback, merely we’ll examine methods to succeed in or to generate N by contemplating each P and Q powers by making recursive calls.
Pseudo Code:
To examine the powers being utilized in recursive relation.
‘lengthy lengthy int a=1;
ans = 1e9; // to retailer potential reply
if(energy = 1){
return n;
}
whereas(n-a >= 0)
{
ans = min(ans, dp[n-a]);
a = a*energy;
}
return ans+1;
Observe the steps talked about beneath to implement the thought:
- Initialize a dp[] array of dimension N+1 and initialize it with 1e9.
- Set, the bottom circumstances, dp[0] = 0 and dp[1] = 1.
- Traverse via 2 to N and discover the methods with powers.
- Way1 by contemplating energy of P.
- Way2 by contemplating energy of Q.
- Take into account dp[i] = min(way1, way2).
- After traversing return dp[N].
Beneath is the implementation of the above strategy.
C++
|
Time Complexity: O(N * logN)
Auxiliary House: O(N * logN)
Associated Articles: