-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPowerSum.java
42 lines (33 loc) · 1.02 KB
/
PowerSum.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import javax.swing.*;
//Find the number of ways that a given integer, X, can be expressed as the sum of the powers of unique, natural numbers.
public class PowerSum {
public static int numWay=0;
public static void powerSum2(int X, int K) {
int curSum = 0;
if(X == 1) {
numWay = 1;
return;
}
powerSumHelper2(X, K, (int) Math.pow(X,1./K),curSum); // X^ 1/k
}
public static void powerSumHelper2(int X, int K, int curNum, int curSum) {
if(curSum == X) {
numWay+=1;
return;
}
if(curNum == 0 || curSum > X)
return;
powerSumHelper2(X, K, curNum-1, curSum);
int times = 1;
for(int i = 0; i < K; i++) {
times*=curNum;
}
powerSumHelper2(X,K, curNum-1, curSum + times);
}
public static void main(String[] args) {
//powerSum1(100,2);
//System.out.println(numWay);
powerSum2(400,2);
System.out.println(numWay);
}
}