-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathArmstrongNumbersMultiSetLong.java
More file actions
97 lines (76 loc) · 2.55 KB
/
ArmstrongNumbersMultiSetLong.java
File metadata and controls
97 lines (76 loc) · 2.55 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ArmstrongNumbersMultiSetLong {
private static long cntSearch;
private static int N;
private static int[] digitsMultiSet;
private static List<Long> results;
private static long maxPow;
private static long minPow;
private static long[][] pows;
private static void genPows(int N) {
if (N > 20) throw new IllegalArgumentException();
pows = new long[10][N + 1];
for (int i = 0; i < pows.length; i++) {
long p = 1;
for (int j = 0; j < pows[i].length; j++) {
pows[i][j] = p;
p *= i;
}
}
}
private static boolean check(long pow) {
cntSearch++;
if (pow >= maxPow) return false;
if (pow < minPow) return false;
int[] testMultiSet = new int[10];
while (pow > 0) {
int i = (int) (pow % 10);
testMultiSet[i]++;
pow = pow / 10;
}
for (int i = 0; i < 10; i++) {
if (testMultiSet[i] != digitsMultiSet[i]) return false;
}
return true;
}
private static void search(int digit, int unused, long pow) {
if (digit == 10) {
if (check(pow)) results.add(pow);
return;
}
if (digit == 9) {
digitsMultiSet[digit] = unused;
search(digit + 1, 0, pow + unused * pows[digit][N]);
} else {
for (int i = 0; i <= unused; i++) {
digitsMultiSet[digit] = i;
search(digit + 1, unused - i, pow + i * pows[digit][N]);
}
}
}
public static List<Long> generate(int maxN) {
if (maxN >= 20) throw new IllegalArgumentException();
genPows(maxN);
results = new ArrayList<>();
digitsMultiSet = new int[10];
cntSearch = 0;
for (N = 1; N <= maxN; N++) {
minPow = (long) Math.pow(10, N - 1);
maxPow = (long) Math.pow(10, N);
search(0, N, 0);
}
// System.out.println(cntSearch); // here we print the number of cases calculated
Collections.sort(results);
return results;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Long> list = generate(19);
long finish = System.currentTimeMillis();
System.out.println("Time consumed: " + (finish - start) + " ms");
System.out.println(list.size());
System.out.println(list);
}
}