Skip to content

Commit 1447db4

Browse files
committed
Refactor PowerSum algorithm implementation and documentation
1 parent f16689e commit 1447db4

File tree

1 file changed

+12
-20
lines changed

1 file changed

+12
-20
lines changed

src/main/java/com/thealgorithms/backtracking/PowerSum.java

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,28 @@
1-
package com.thealgorithms.backtracking;
2-
3-
/**
4-
* Problem Statement:
5-
* Find the number of ways that a given integer, N, can be expressed as the sum of the Xth powers
6-
* 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.
8-
* The only solution is 1^3 + 2^3 + 3^3 + 4^3. Therefore, the output will be 1.
9-
*
10-
* N is represented by the parameter 'targetSum' in the code.
11-
* X is represented by the parameter 'power' in the code.
12-
*/
131
public class PowerSum {
142

153
/**
164
* Calculates the number of ways to express the target sum as a sum of Xth powers of unique natural numbers.
175
*
18-
* targetSum The target sum to achieve (N in the problem statement)
19-
* power The power to raise natural numbers to (X in the problem statement)
20-
* The number of ways to express the target sum
6+
* @param targetSum The target sum to achieve (N in the problem statement)
7+
* @param power The power to raise natural numbers to (X in the problem statement)
8+
* @return The number of ways to express the target sum
219
*/
2210
public int powSum(int targetSum, int power) {
11+
// Special case: when both targetSum and power are zero
12+
if (targetSum == 0 && power == 0) {
13+
return 1; // by convention, one way to sum to zero: use nothing
14+
}
2315
return sumRecursive(targetSum, power, 1, 0);
2416
}
2517

2618
/**
2719
* Recursively calculates the number of ways to express the remaining sum as a sum of Xth powers.
2820
*
29-
* remainingSum The remaining sum to achieve
30-
* power The power to raise natural numbers to (X in the problem statement)
31-
* currentNumber The current natural number being considered
32-
* currentSum The current sum of powered numbers
33-
* The number of valid combinations
21+
* @param remainingSum The remaining sum to achieve
22+
* @param power The power to raise natural numbers to (X in the problem statement)
23+
* @param currentNumber The current natural number being considered
24+
* @param currentSum The current sum of powered numbers
25+
* @return The number of valid combinations
3426
*/
3527
private int sumRecursive(int remainingSum, int power, int currentNumber, int currentSum) {
3628
int newSum = currentSum + (int) Math.pow(currentNumber, power);

0 commit comments

Comments
 (0)