Find the minimum number to be added to N to make it a power of K
Last Updated :
16 Nov, 2021
Given two positive integers N and K, the task is to find the minimum number to be added to N to make it a power of K.
Examples:
Input: N = 9, K = 10
Output: 1
Explanation:
9 + 1 = 10 = 101
Input: N = 20, K = 5
Output: 5
Explanation:
20 + 5 = 25 = 52
Approach: The idea to solve this problem is to observe that the minimum power of K which can be formed from N is the next greater power of K. So, the idea is to find the next greater power of K and find the difference between N and this number. The next greater power of K can be found by the formula,
Kint(log(N)/log(K)) + 1
Therefore, the minimum number to be added can be computed by:
Minimum Number = Kint(log(N)/log(K)) + 1 – N
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int minNum( int n, int k)
{
int x = ( int )( log (n) / log (k)) + 1;
int mn = pow (k, x) - n;
return mn;
}
int main()
{
int n = 20, k = 5;
cout << minNum(n, k);
return 0;
}
|
Java
class GFG{
static int minNum( int n, int k)
{
int x = ( int )(Math.log(n) / Math.log(k)) + 1 ;
int mn = ( int ) (Math.pow(k, x) - n);
return mn;
}
public static void main(String[] args)
{
int n = 20 , k = 5 ;
System.out.print(minNum(n, k));
}
}
|
Python3
import math
def minNum(n, k):
x = int ((math.log(n) / / math.log(k))) + 1
mn = pow (k, x) - n
return mn
if __name__ = = '__main__' :
n = 20
k = 5
print (minNum(n, k))
|
C#
using System;
class GFG{
static int minNum( int n, int k)
{
int x = ( int )(Math.Log(n) /
Math.Log(k)) + 1;
int mn = ( int )(Math.Pow(k, x) - n);
return mn;
}
public static void Main( string [] args)
{
int n = 20, k = 5;
Console.Write(minNum(n, k));
}
}
|
Javascript
<script>
function minNum(n, k)
{
var x = parseInt(Math.log(n) / Math.log(k)) + 1;
var mn = Math.pow(k, x) - n;
return mn;
}
var n = 20, k = 5;
document.write( minNum(n, k));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...