|
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 |
| - */ |
13 | 1 | public class PowerSum {
|
14 | 2 |
|
15 | 3 | /**
|
16 | 4 | * Calculates the number of ways to express the target sum as a sum of Xth powers of unique natural numbers.
|
17 | 5 | *
|
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 |
21 | 9 | */
|
22 | 10 | 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 | + } |
23 | 15 | return sumRecursive(targetSum, power, 1, 0);
|
24 | 16 | }
|
25 | 17 |
|
26 | 18 | /**
|
27 | 19 | * Recursively calculates the number of ways to express the remaining sum as a sum of Xth powers.
|
28 | 20 | *
|
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 |
34 | 26 | */
|
35 | 27 | private int sumRecursive(int remainingSum, int power, int currentNumber, int currentSum) {
|
36 | 28 | int newSum = currentSum + (int) Math.pow(currentNumber, power);
|
|
0 commit comments