C++ program to find ways an integer can be expressed as sum of n-th power of unique natural numbers


In this article, we will be discussing a program to find ways an integer (say X) can be expressed as sum of n-th power of unique natural numbers.

For example, let X = 100 and n = 2

Then there would be 3 ways to express 100 as sum of squares of natural numbers.

100 = 102
100 = 62 + 82
100 = 12 + 32 + 42 + 52 + 72

This can be done easily by using recursion. We would start from 1 and go till the n-th root of the given number. In every run, we would subtract the n-th power of natural numbers (starting from 1) from the given number till the number become less than. This would give us the ways the number can be represented in as sum of n-th powers of natural numbers.

Example

 Live Demo

#include<iostream>
#include <math.h>
using namespace std;
int result = 0;
int ways(int number, int a, int init, int n){
   if (a == 0) {
      result++;
   }
   //setting the higher limit
   int max = (int)floor(pow(number, 1.0 / n));
   for (int i = init + 1; i <= max; i++) {
      //subtracting n-th power values starting from 1
      int b = a - (int)pow(i, n);
      if (b >= 0)
         ways(number, a - (int)pow(i, n), i, n);
   }
   return result;
}
int main() {
   int a = 100, n = 2;
   cout << ways(a, a, 0, n);
   return 0;
}

Output

3

Updated on: 03-Oct-2019

626 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements