- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 = (3^{2} + 3^{1} + 3^{1})

## 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

- Related Questions & Answers
- Minimum Fibonacci terms with sum equal to K in C++
- Minimum number of single digit primes required whose sum is equal to N in C++
- Program to find equal sum arrays with minimum number of operations in Python
- Minimum number of squares whose sum equals to given number n
- Minimum number of palindromes required to express N as a sum using C++.
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- C++ find four factors of N with maximum product and sum equal to N .
- Finding n subarrays with equal sum in JavaScript
- Minimum number of moves to make all elements equal using C++.
- Minimum numbers which is smaller than or equal to N and with sum S in C++
- Find minimum sum of factors of number using C++.
- Find four factors of N with maximum product and sum equal to N in C++
- Find a Number X whose sum with its digits is equal to N in C++
- Minimum number of given operations required to make two strings equal using C++.
- Find four factors of N with maximum product and sum equal to N - Set-2 in Python

Advertisements