Open In App

Find the power of K nearest to N

Last Updated : 29 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. For the number N, find the nearest powers of K greater and smaller.
  2. 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]
  3. 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]
  4. 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 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




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to find nearest power
function 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 Code
let N = 32, K = 7;
 
document.write(nearestPowerOfK(N, K));
 
// This code is contributed by Potta Lokesh
 
</script>


Output

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.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the nearest power of k to n
int nearest_power(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;
        long power = 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
    long power1 = pow(k, low);
    long power2 = pow(k, high);
 
    if (abs(power1 - n) <= abs(power2 - n)) {
        return power1;
    }
    else {
        return power2;
    }
}
 
int main()
{
    int n = 32;
    int k = 7;
 
    cout << nearest_power(n, k) << endl;
 
    return 0;
}


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=32
k=7
print(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=32
let k=7
console.log(nearest_power(n, k))


Output

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads