- 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

# 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^{2}100 = 6^{2}+ 8^{2}100 = 1^{2}+ 3^{2}+ 4^{2}+ 5^{2}+ 7^{2}

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

- Related Questions & Answers
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers in C++
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- Java program to find the sum of n natural numbers
- Check if an integer can be expressed as a sum of two semi-primes in Python
- C++ Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- Java Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- 8085 program to find the sum of first n natural numbers
- Program to find sum of first n natural numbers in C++
- Program to find number of ways we can get a number which is sum of nth power of unique numbers in Python
- C program for a number to be expressed as a sum of two prime numbers.
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Find m-th summation of first n natural numbers in C++
- Sum of first n natural numbers in C Program
- Java Program to cube sum of first n natural numbers
- PHP program to find the sum of cubes of the first n natural numbers

Advertisements