Friday, September 22, 2023
HomeSoftware DevelopmentMinimal powers of P and Q to signify N

Minimal powers of P and Q to signify N


Enhance Article

Save Article

Like Article

Enhance Article

Save Article

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++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

int examine(int n, int energy, vector<int>& dp)

{

    

    lengthy lengthy int a = 1;

    int ans = 1e9;

  

    

    if (energy == 1)

        return n;

  

    

    whereas (n - a >= 0) {

        ans = min(ans, dp[n - a]);

        a = a * energy;

    }

  

    return ans + 1;

}

  

int strikes(int n, int p, int q)

{

    

    vector<int> dp(n + 1, 1e9);

  

    

    dp[0] = 0;

    dp[1] = 1;

  

    for (int i = 2; i <= n; ++i) {

        int way1 = examine(i, p, dp);

        int way2 = examine(i, q, dp);

        dp[i] = min(way1, way2);

    }

  

    

    return dp[n];

}

  

int important()

{

    int N = 15, P = 2, Q = 1;

  

    

    cout << strikes(N, P, Q) << endl;

    return 0;

}

Time Complexity: O(N * logN)
Auxiliary House:  O(N * logN)

Associated Articles:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments