Skip to content

Commit 87e10d6

Browse files
authored
Add Power Sum (fixes TheAlgorithms#2634) (TheAlgorithms#2645)
1 parent 2eb6d5c commit 87e10d6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Backtracking/PowerSum.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package Backtracking;
2+
3+
import java.util.Scanner;
4+
/*
5+
* Problem Statement :
6+
* Find the number of ways that a given integer, N , can be expressed as the sum of the Xth powers of unique, natural numbers.
7+
* For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. The only solution is 1^3+2^3+3^3+4^3.
8+
* Therefore output will be 1.
9+
*/
10+
public class PowerSum {
11+
12+
public static void main(String[] args) {
13+
Scanner sc = new Scanner(System.in);
14+
System.out.println("Enter the number and the power");
15+
int N = sc.nextInt();
16+
int X = sc.nextInt();
17+
PowerSum ps = new PowerSum();
18+
int count = ps.powSum(N,X);
19+
//printing the answer.
20+
System.out.println("Number of combinations of different natural number's raised to "+X+" having sum "+N+" are : ");
21+
System.out.println(count);
22+
sc.close();
23+
}
24+
private int count = 0,sum=0;
25+
public int powSum(int N, int X) {
26+
Sum(N,X,1);
27+
return count;
28+
}
29+
//here i is the natural number which will be raised by X and added in sum.
30+
public void Sum(int N, int X,int i) {
31+
//if sum is equal to N that is one of our answer and count is increased.
32+
if(sum == N) {
33+
count++;
34+
return;
35+
}
36+
//we will be adding next natural number raised to X only if on adding it in sum the result is less than N.
37+
else if(sum+power(i,X)<=N) {
38+
sum+=power(i,X);
39+
Sum(N,X,i+1);
40+
//backtracking and removing the number added last since no possible combination is there with it.
41+
sum-=power(i,X);
42+
}
43+
if(power(i,X)<N) {
44+
//calling the sum function with next natural number after backtracking if when it is raised to X is still less than X.
45+
Sum(N,X,i+1);
46+
}
47+
}
48+
//creating a separate power function so that it can be used again and again when required.
49+
private int power(int a , int b ){
50+
return (int)Math.pow(a,b);
51+
}
52+
}

0 commit comments

Comments
 (0)