Find the power of K nearest to N

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:
- For the number N, find the nearest powers of K greater and smaller.
- The smaller power of K will be the floor value (say X) of logKN. So the value will be pow(K, X). [floor value of P = closest integer to P which is ≤ P]
- And greater power of K will be the ceiling value (say Y) of logKN. So the value will be pow(K, Y). [ceiling value of P = closest integer to P which is ≥ P]
- Calculate the difference of these two values from N and print the nearest as specified in the problem statement.
Below is the implementation of the above approach.
C++
// C++ program to// implement the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find nearest powerint 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 Codeint main(){Â Â Â Â int N = 32, K = 7;Â Â Â Â cout << nearestPowerOfK(N, K);Â Â Â Â return 0;} |
Java
// Java implementation for the above approachimport java.util.*;public class GFG{Â
// Function to find nearest powerstatic 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 Codepublic 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 approachimport mathÂ
# Function to find nearest powerdef 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 Codeif __name__ == "__main__":Â
    N = 32    K = 7         print(nearestPowerOfK(N, K))Â
# This code is contributed by rakeshsahni |
C#
// C# implementation for the above approachusing System;class GFG{Â
// Function to find nearest powerstatic 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 Codepublic static void Main(){Â Â Â Â int N = 32, K = 7;Â
    Console.Write(nearestPowerOfK(N, K));}}Â
// This code is contributed by Samim Hossain Mondal. |
Javascript
<script>Â
// JavaScript program to implement// the above approach Â
// Function to find nearest powerfunction nearestPowerOfK(N, K) {         // Finding log of the element    let lg = Math.floor(Math.log(N) /                         Math.log(K));Â
    // Calculating the two possible    // nearest values    let a = Math.pow(K, lg);    let b = Math.pow(K, lg + 1);Â
    // Finding the closest one    if ((N - a) < (b - N))        return a;             return b;}Â
// Driver Codelet N = 32, K = 7;Â
document.write(nearestPowerOfK(N, K));Â
// This code is contributed by Potta LokeshÂ
</script> |
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)
Approach#2: Using binary search
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.
Algorithm
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.
Java
public class GFG {    // Function to find the nearest power of k to n    public static int nearestPower(int n, int k) {        // Initialize the search space        int low = 0;        int high = n;                 // Perform binary search to find the nearest power of k to n        while (low <= high) {            int mid = (low + high) / 2;            int power = (int) Math.pow(k, mid);                         if (power == n) {                return power;            } else if (power < n) {                low = mid + 1;            } else {                high = mid - 1;            }        }                 // Find the closest power of k to n among the two adjacent powers        int power1 = (int) Math.pow(k, low);        int power2 = (int) Math.pow(k, high);                 if (Math.abs(power1 - n) <= Math.abs(power2 - n)) {            return power1;        } else {            return power2;        }    }Â
    public static void main(String[] args) {        int n = 32;        int k = 7;Â
        // Function Call        System.out.println(nearestPower(n, k));    }} |
Python3
def nearest_power(n, k):    # Initialize the search space    low = 0    high = n    # Perform binary search to find the nearest power of k to n    while low <= high:        mid = (low + high) // 2        power = k ** mid        if power == n:            return power        elif power < n:            low = mid + 1        else:            high = mid - 1    # Find the closest power of k to n among the two adjacent powers    power1 = k ** low    power2 = k ** high    if abs(power1 - n) <= abs(power2 - n):        return power1    else:        return power2Â
n=32k=7print(nearest_power(n, k)) |
C#
using System;Â
class Program{    // Function to find the nearest power of k to n    static int NearestPower(int n, int k)    {        // Initialize the search space        int low = 0;        int high = n;Â
        // Perform binary search to find the nearest power of k to n        while (low <= high)        {            int mid = (low + high) / 2;            double power = Math.Pow(k, mid);Â
            if (power == n)            {                return (int)power;            }            else if (power < n)            {                low = mid + 1;            }            else            {                high = mid - 1;            }        }Â
        // Find the closest power of k to n among the two adjacent powers        double power1 = Math.Pow(k, low);        double power2 = Math.Pow(k, high);Â
        if (Math.Abs(power1 - n) <= Math.Abs(power2 - n))        {            return (int)power1;        }        else        {            return (int)power2;        }    }Â
    static void Main()    {        int n = 32;        int k = 7;Â
        // Function Call        Console.WriteLine(NearestPower(n, k));    }} |
Javascript
function nearest_power(n, k){    // Initialize the search space    let low = 0;    let high = n;    // Perform binary search to find the nearest power of k to n    while (low <= high){        let mid = Math.floor((low + high) / 2);        let power = Math.pow(k , mid);        if (power == n)            return power;        else if (power < n)            low = mid + 1;        else            high = mid - 1;    }    // Find the closest power of k to n among the two adjacent powers    power1 = Math.pow(k , low);    power2 = Math.pow(k , high);    if (Math.abs(power1 - n) <= Math.abs(power2 - n))        return power1;    else        return power2;}Â
let n=32let k=7console.log(nearest_power(n, k)) |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



