Minimum number of power terms with sum equal to n using C++.


Problem statement

Given two positive integer N and X. The task is to express N as a sum of powers of X (X0 + X1 +…..+ Xn) such that the number of powers of X should be minimum.

Print the minimum number of power of N used to make the sum equal to N.

If N = 15 and X = 3 then we need 3 powers of ‘3’ as follows −

15 = (32 + 31 + 31)

Algorithm

Use below formula to calculate final result −

1. If x = 1, then answer will be n only (n = 1 + 1 +…. n times)s
2. Any number n can be expressed as, n = x * a + b where 0 −= b −= x-1. Now since b is between 0 to x – 1, then b should be expressed as sum of x0 b times

Example

#include <iostream>
using namespace std;
int minNumOfPower(int n, int x){
   if (x == 1) {
      return n;
   }
   int result = 0;
   while (n > 0) {
      result = result + (n % x);
      n = n / x;
   }
   return result;
}
int main(){
   int n = 15;
   int x = 3;
   cout << "Minimum number of powers = " <<
   minNumOfPower(15, 3) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Minimum number of powers = 3

Updated on: 31-Oct-2019

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements