📜  找出要加到N的最小数,使其成为K的幂

📅  最后修改于: 2021-04-21 22:45:23             🧑  作者: Mango

给定两个正整数NK ,任务是找到要加到N的最小数以使其成为K的幂。
例子:

方法:解决此问题的想法是观察可以由N形成的K的最小幂是K的下一个更大的幂。因此,想法是找到K的下一个更大的幂并找出N之间的差。还有这个号码可以通过以下公式找到K的下一个更大的幂:

因此,可以通过以下方式计算要添加的最小数量:

下面是上述方法的实现:

C++
// C++ program to find the minimum number
// to be added to N to make it a power of K
 
#include 
#define ll long long int
using namespace std;
 
// Function to return the minimum number
// to be added to N to make it a power of K.
int minNum(int n, int k)
{
    int x = (int)(log(n) / log(k)) + 1;
 
    // Computing the difference between
    // then next greater power of K
    // and N
    int mn = pow(k, x) - n;
    return mn;
}
 
// Driver code
int main()
{
    int n = 20, k = 5;
    cout << minNum(n, k);
    return 0;
}


Java
// Java program to find the minimum number
// to be added to N to make it a power of K
 
class GFG{
  
// Function to return the minimum number
// to be added to N to make it a power of K.
static int minNum(int n, int k)
{
    int x = (int)(Math.log(n) / Math.log(k)) + 1;
  
    // Computing the difference between
    // then next greater power of K
    // and N
    int mn = (int) (Math.pow(k, x) - n);
    return mn;
}
  
// Driver code
public static void main(String[] args)
{
    int n = 20, k = 5;
    System.out.print(minNum(n, k));
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program to find the minimum number
# to be added to N to make it a power of K
import math
 
# Function to return the minimum number
# to be added to N to make it a power of K.
def minNum(n, k):
     
    x = int((math.log(n) // math.log(k))) + 1
     
    # Computing the difference between
    # then next greater power of K
    # and N
    mn = pow(k, x) - n
    return mn
     
# Driver code
if __name__=='__main__':
     
    n = 20
    k = 5
    print(minNum(n, k))
 
# This code is contributed by rutvik_56


C#
// C# program to find the minimum number
// to be added to N to make it a power of K
using System;
class GFG{
   
// Function to return the minimum number
// to be added to N to make it a power of K.
static int minNum(int n, int k)
{
    int x = (int)(Math.Log(n) /
                  Math.Log(k)) + 1;
   
    // Computing the difference between
    // then next greater power of K
    // and N
    int mn = (int)(Math.Pow(k, x) - n);
    return mn;
}
   
// Driver code
public static void Main(string[] args)
{
    int n = 20, k = 5;
    Console.Write(minNum(n, k));
}
}
  
// This code is contributed by Ritik Bansal


Javascript


输出:
5