Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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 = 10<sup>2</sup> 100 = 6<sup>2</sup> + 8<sup>2</sup> 100 = 1<sup>2</sup> + 3<sup>2</sup> + 4<sup>2</sup> + 5<sup>2</sup> + 7<sup>2</sup>
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
#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
Advertisements
