![]() |
VOOZH | about |
Given two integers N & K. The task is to find the nearest power of K for the integer N. If there are two nearest powers, consider the larger one.
Examples:
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.
Approach: Follow the below steps to solve this problem:
Below is the implementation of the above approach.
49
Time Complexity: O(log (N)) as pow function takes logarithmic time to execute so overall complexity turns out to be log N
Auxiliary Space: O(1)
This approach uses a binary search approach to find the nearest power of k to n. It starts by initializing a search space, which consists of the range of integers from 0 to n. Then, it performs a binary search by computing the power of k at the midpoint of the search space, and comparing it to n. If the power of k is equal to n, the function returns that power. If the power of k is less than n, the search space is narrowed to the upper half of the current range. Otherwise, the search space is narrowed to the lower half of the current range. The binary search continues until the closest power of k to n is found.
1. Initialize the search space with low = 0 and high = n.
2. While the search space is not empty, do the following:
a. Compute the midpoint of the search space using mid = (low + high) // 2.
b. Compute the power of k at the midpoint using power = k ** mid.
c. If power is equal to n, return power.
d. If power is less than n, update low to mid + 1.
e. If power is greater than n, update high to mid - 1.
3. Find the closest power of k to n among the two adjacent powers by computing power1 = k ** low and power2 = k ** high.
4. Return the closest power of k to n among power1 and power2.
49
Time complexity: O(log n), as the binary search algorithm reduces the search space by half in each iteration.
Space complexity: O(1), as it only uses a few variables to store the current search space, the midpoint, and the powers of k.