求最接近 N 的 K 的幂
给定两个整数N和K。任务是找到整数 N 的最接近 K 的幂。如果有两个最接近的幂,则考虑较大的那个。
例子:
Input: N = 5, K = 3
Output: 3
Explanation: The powers of 3 are 3, 9, 27, . . . Among these 3 is the nearest to 5 as it has a distance of 2.
Input: N = 32, K = 7
Output: 49
Explanation: The powers of 7 are 7, 49, 343, . . . 49 is the closest to 32 among these numbers.
Input: N = 6, K = 3
Output: 9
Explanation: Both 3 and 9 have distance = 3. But 9 is larger between 3 and 9.
方法:按照以下步骤解决此问题:
- 对于数字N ,找出 K 的最近的越来越大的幂。
- K 的较小幂将是log K N的底值(例如 X)。所以值将是pow(K, X) 。 [P 的下限值 = 最接近 P 的整数,即 ≤ P]
- K 的更大功率将是log K N的上限值(例如 Y)。所以值将是pow(K, Y) 。 [P 的上限值 = 最接近 P 的整数,即 ≥ P]
- 计算这两个值与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)