Compute the maximum power with a given condition
Given 3 integers N, M, and K. The task is to find maximum P such that N * KP ? M.
Examples:
Input :N = 1, K = 2, M = 5
Output :2
Explanation: 1*2² = 5, which is <= to M(5), also for p = 3 the value would be 1*2³=9, this is not a feasible solution. Thus 2 is the answer.
Input: N = 5, K = 25, M = 100
Output: 0
Explanation: 5*25?=5, which is <= to M(100), also for p =1 the value would be 125, which is greater than the M(100), thus not a feasible solution. Hence 0 is the required answer.
Approach:
In this algorithm, simply multiply N with K and update the current value of N with the result and increase variable power (initially 0) by 1.
To achieve this, a recursive function is defined which has 2 base cases.
- Initially, N is greater than required, therefore, return 0.
- Otherwise, return power – 1.
- If the current value of N is equal to the M then return power.
- Recursive condition if current N < M:
? Update N as (N * k) and power as current power + 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int calculate(ll int n, ll int k,
ll int m, ll int power)
{
if (n > m) {
if (power == 0)
return 0;
else
return power - 1;
}
else if (n == m)
return power;
else
return calculate(n * k, k, m, power + 1);
}
int main()
{
ll N = 1, K = 2, M = 5;
cout << calculate(N, K, M, 0);
return 0;
}
|
Java
class GFG
{
static int calculate( int n, int k,
int m, int power)
{
if (n > m)
{
if (power == 0 )
return 0 ;
else
return power - 1 ;
}
else if (n == m)
return power;
else
return calculate(n * k, k, m,
power + 1 );
}
public static void main (String[] args)
{
int N = 1 , K = 2 , M = 5 ;
System.out.println(calculate(N, K, M, 0 ));
}
}
|
Python
def calculate(n, k, m, power):
if n > m:
if power = = 0 :
return 0
else :
return power - 1
elif n = = m:
return power
else :
return calculate(n * k, k, m, power + 1 )
if __name__ = = "__main__" :
N = 1
K = 2
M = 5
print (calculate(N, K, M, 0 ))
|
C#
using System;
class GFG
{
static int calculate( int n, int k,
int m, int power)
{
if (n > m)
{
if (power == 0)
return 0;
else
return power - 1;
}
else if (n == m)
return power;
else
return calculate(n * k, k, m,
power + 1);
}
public static void Main (String[] args)
{
int N = 1, K = 2, M = 5;
Console.WriteLine(calculate(N, K, M, 0));
}
}
|
Javascript
<script>
function calculate(n , k , m , power) {
if (n > m) {
if (power == 0)
return 0;
else
return power - 1;
}
else if (n == m)
return power;
else
return calculate(n * k, k, m, power + 1);
}
var N = 1, K = 2, M = 5;
document.write(calculate(N, K, M, 0));
</script>
|
Time Complexity:– O(1)
Auxiliary Space: O(1), as no extra space is used.
Last Updated :
08 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...