Open In App

Minimum operation required to make N as sum of distinct powers of X

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

Given an integer N and a base X, the task is to find the minimum number of operations required to represent N as a sum of the distinct powers of X. In each operation, you can either increment or decrement N. You are allowed to make the given operation any number of times

Examples:

Input: N = 7, X = 3 
Output: 3
Explanation: It will be optimal to increment N by 3 in 3 operations. Then, N = 10 = 30 + 33.  

Input: N = 53, X = 7 
Output: 3
Explanation: It can be verified that it will be optimal to decrement N by 3 using operation 3 times. Then, N = 50 = 70 + 72.

Approach: Implement the idea below to solve the problem

The problem is simple Greedy Logic based. The key observation is we have to find the sum of two distinct powers, Which is nearest to the N. After finding such a pair of powers of X, Just output the absolute difference between sum of powers and N.  

Steps were taken to solve the problem:

  • Create an ArrayList let’s say list for storing all powers of X till less than 105.
  • Initialize a variable let’s say min for storing a minimum number of operations required.
  • Run two nested loops for i = 0 to i < list.size() and j = 0 to j < list.size() and follow below mentioned steps under the scope of the loop:
    • If (i == j), then continue;
    • Else, get some of the different powers at index i and j in the list and update min, If the absolute difference between sum and N is less than the previously stored value in the min variable.
  • Return the value of min.

Below is the code to implement the approach:

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function for returning minimum
// MinOperations
int MinOperations(int N, int X)
{
 
    // ArrayList to store the powers
    // less than or equal to 10^5
    // for any X
    vector<int> list;
 
    // Power Counter
    int counter = 0;
 
    // Variable for storing minimum
    // operations
    int min = INT_MAX;
 
    // While Loop for initializing
    // list of powers
    while (pow(X, counter) <= pow(10, 5)) {
        list.push_back(pow(X, counter));
        counter++;
    }
 
    // Nested loops to traverse list
    // So we can find nearest sum
    // of distinct powers of X
    for (int i = 0; i < list.size(); i++) {
        for (int j = 0; j < list.size(); j++) {
            if (i == j)
                continue;
            else {
 
                // Variable to hold
                // sum of different
                // powers
                int sum = list[i] + list[j];
 
                // If it is nearest to
                // N, then update min
                min = abs(sum - N) < min ? abs(sum - N)
                                         : min;
            }
        }
    }
    
 
    // Returning the minimum number
    // of operations required
    return (min);
}
 
// Driver code
int main()
{
    int N = 6;
    int X = 2;
 
    // Function call
    cout << MinOperations(N, X);
 
    return 0;
}
 
// This code is contributed by Tapesh(tapeshdua420)


Java




// Java code to implement the approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args)
        throws java.lang.Exception
    {
        int N = 6;
        int X = 2;
 
        // Function call
        System.out.println(MinOperations(N, X));
    }
 
    // Method for returning minimum
    // MinOperations
    static int MinOperations(int N, int X)
    {
 
        // ArrayList to store the powers
        // less than or equal to 10^5
        // for any X
        ArrayList<Integer> list = new ArrayList<>();
 
        // Power Counter
        int counter = 0;
 
        // Variable for storing minimum
        // operations
        int min = Integer.MAX_VALUE;
 
        // While Loop for initializing
        // list of powers
        while ((int)(Math.pow(X, counter))
               <= (int)Math.pow(10, 5)) {
            list.add((int)(Math.pow(X, counter)));
            counter++;
        }
 
        // Nested loops to traverse list
        // So we can find nearest sum
        // of distinct powers of X
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (i == j)
                    continue;
                else {
 
                    // Variable to hold
                    // sum of different
                    // powers
                    int sum = list.get(i) + list.get(j);
 
                    // If it is nearest to
                    // N, then update min
                    min = abs(sum - N) < min ? abs(sum - N)
                                             : min;
                }
            }
        }
       // System.out.println(list);
 
        // Returning the minimum number
        // of operations required
        return (min);
    }
 
    // Method for returning
    // absolute values
    static int abs(int a) { return a < 0 ? -a : a; }
}


Python3




# Nikunj Sonigara
 
def min_operations(N, X):
    powers_list = []
    counter = 0
    min_val = float('inf')
 
    while X ** counter <= 10 ** 5:
        powers_list.append(X ** counter)
        counter += 1
 
    for i in range(len(powers_list)):
        for j in range(len(powers_list)):
            if i == j:
                continue
            else:
                current_sum = powers_list[i] + powers_list[j]
                min_val = min(abs(current_sum - N), min_val)
 
    return min_val
 
def main():
    N = 6
    X = 2
    print(min_operations(N, X))
 
if __name__ == "__main__":
    main()


C#




// C# code addition
using System;
using System.Collections.Generic;
 
class GFG
{
    public static void Main(string[] args)
    {
        int N = 6;
        int X = 2;
 
        // Function call
        Console.WriteLine(MinOperations(N, X));
    }
 
    // Method for returning minimum
    // MinOperations
    static int MinOperations(int N, int X)
    {
 
        // List to store the powers
        // less than or equal to 10^5
        // for any X
        List<int> list = new List<int>();
 
        // Power Counter
        int counter = 0;
 
        // Variable for storing minimum
        // operations
        int min = int.MaxValue;
 
        // While Loop for initializing
        // list of powers
        while ((int)(Math.Pow(X, counter))
               <= (int)Math.Pow(10, 5))
        {
            list.Add((int)(Math.Pow(X, counter)));
            counter++;
        }
 
        // Nested loops to traverse list
        // So we can find nearest sum
        // of distinct powers of X
        for (int i = 0; i < list.Count; i++)
        {
            for (int j = 0; j < list.Count; j++)
            {
                if (i == j)
                    continue;
                else
                {
 
                    // Variable to hold
                    // sum of different
                    // powers
                    int sum = list[i] + list[j];
 
                    // If it is nearest to
                    // N, then update min
                    min = Math.Abs(sum - N) < min ? Math.Abs(sum - N)
                                                 : min;
                }
            }
        }
 
        // Returning the minimum number
        // of operations required
        return min;
    }
 
    // Method for returning
    // absolute values
    static int Abs(int a) { return a < 0 ? -a : a; }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




function MinOperations(N, X) {
    // Array to store powers less than or
    // equal to 10^5 for any X
    const list = [];
    let counter = 0;
    let min = Infinity;
    // While loop to initialize the list of powers
    while (Math.pow(X, counter) <= Math.pow(10, 5)) {
        list.push(Math.pow(X, counter));
        counter++;
    }
    // Nested loops to traverse the
    // list and find nearest sum
    // of distinct powers of X
    for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < list.length; j++) {
            if (i === j) continue;
            // Calculate the sum of different powers
            const sum = list[i] + list[j];
            // Update min if sum is closer to N
            min = Math.abs(sum - N) < min ? Math.abs(sum - N) : min;
        }
    }
    // Return the minimum number of
    // operations required
    return min;
}
// Driver code
const N = 6;
const X = 2;
// Function call and output
console.log(MinOperations(N, X));


Output

0





Time Complexity: O(17*17) ~ O(1), As the Maximum length of the list can be at most 17, Then the total number of loops will iterate 17*17 times.
Auxiliary Space: O(17) ~ O(1), As the Maximum length of the list can be 17, Which is for X = 2.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads