📜  求最接近 N 的 K 的幂

📅  最后修改于: 2022-05-13 01:56:06.449000             🧑  作者: Mango

求最接近 N 的 K 的幂

给定两个整数NK。任务是找到整数 N 的最接近 K 的幂。如果有两个最接近的幂,则考虑较大的那个。

例子:

方法:按照以下步骤解决此问题:

  1. 对于数字N ,找出 K 的最近的越来越大的幂。
  2. K 的较小幂将是log K N底值(例如 X)。所以值将是pow(K, X) 。 [P 的下限值 = 最接近 P 的整数,即 ≤ P]
  3. K 的更大功率将是log K N上限值(例如 Y)。所以值将是pow(K, Y) 。 [P 的上限值 = 最接近 P 的整数,即 ≥ P]
  4. 计算这两个值与N的差值并打印问题陈述中指定的最接近的值。

下面是上述方法的实现。

C++
// C++ program to
// implement the above approach
#include 
using namespace std;
 
// Function to find nearest power
int nearestPowerOfK(int N, int K)
{
    // Finding log of the element
    int lg = log(N) / log(K);
 
    // Calculating the two possible
    // nearest values
    int a = pow(K, lg);
    int b = pow(K, lg + 1);
 
    // Finding the closest one
    if ((N - a) < (b - N))
        return a;
    return b;
}
 
// Driver Code
int main()
{
    int N = 32, K = 7;
    cout << nearestPowerOfK(N, K);
    return 0;
}


Java
// Java implementation for the above approach
import java.util.*;
public class GFG
{
 
// Function to find nearest power
static int nearestPowerOfK(int N, int K)
{
    // Finding log of the element
    int lg = (int)(Math.log(N) / Math.log(K));
 
    // Calculating the two possible
    // nearest values
    int a = (int)Math.pow(K, lg);
    int b = (int)Math.pow(K, lg + 1);
 
    // Finding the closest one
    if ((N - a) < (b - N))
        return a;
    return b;
}
 
// Driver Code
public static void main(String args[])
{
    int N = 32, K = 7;
 
    System.out.println(nearestPowerOfK(N, K));
}
}
 
// This code is contributed by Samim Hossain Mondal.


Python3
# Python3 program to implement the above approach
import math
 
# Function to find nearest power
def nearestPowerOfK(N, K):
     
    # Finding log of the element
    lg = math.log(N) // math.log(K)
 
    # Calculating the two possible
    # nearest values
    a = int(pow(K, lg))
    b = int(pow(K, lg + 1))
 
    # Finding the closest one
    if ((N - a) < (b - N)):
        return a
         
    return b
 
# Driver Code
if __name__ == "__main__":
 
    N = 32
    K = 7
     
    print(nearestPowerOfK(N, K))
 
# This code is contributed by rakeshsahni


C#
// C# implementation for the above approach
using System;
class GFG
{
 
// Function to find nearest power
static int nearestPowerOfK(int N, int K)
{
    // Finding log of the element
    int lg = (int)(Math.Log(N) / Math.Log(K));
 
    // Calculating the two possible
    // nearest values
    int a = (int)Math.Pow(K, lg);
    int b = (int)Math.Pow(K, lg + 1);
 
    // Finding the closest one
    if ((N - a) < (b - N))
        return a;
    return b;
}
 
// Driver Code
public static void Main()
{
    int N = 32, K = 7;
 
    Console.Write(nearestPowerOfK(N, K));
}
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript


输出
49

时间复杂度: O(1)
辅助空间: O(1)