-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathArmstrongNumbersHash.java
More file actions
78 lines (66 loc) · 2.28 KB
/
ArmstrongNumbersHash.java
File metadata and controls
78 lines (66 loc) · 2.28 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
import java.util.*;
public class ArmstrongNumbersHash {
private static Map<Long, List<Long>> reach;
private static List<Long> results;
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 void searchSecondHalf(int depth, int target, long number, long pow) {
if (depth == target / 2) {
long p = pow - number;
if (!reach.containsKey(p)) reach.put(p, new ArrayList<>());
reach.get(p).add(number);
return;
}
number *= 10;
for (int i = 0; i < 10; i++) {
searchSecondHalf(depth + 1, target, number + i, pow + pows[i][target]);
}
}
private static void searchFirstHalf(int depth, int target, long number, long pow) {
if (depth == (target + 1) / 2) {
number = number * (long) Math.pow(10, target / 2);
long p = number - pow;
if (reach.containsKey(p)) {
for (Long l : reach.get(p)) {
results.add(number + l);
}
}
return;
}
number *= 10;
for (int i = 0; i < 10; i++) {
if (i == 0 && depth == 0) continue;
searchFirstHalf(depth + 1, target, number + i, pow + pows[i][target]);
}
}
public static List<Long> generate(int maxN) {
genPows(maxN);
results = new ArrayList<>();
reach = new HashMap<>();
for (int N = 1; N <= maxN; N++) {
reach.clear();
searchSecondHalf(0, N, 0L, 0L);
searchFirstHalf(0, N, 0L, 0L);
}
Collections.sort(results);
return results;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
List<Long> list = generate(9);
long finish = System.currentTimeMillis();
System.out.println("Time consumed: " + (finish - start) + " ms");
System.out.println(list.size());
System.out.println(list);
}
}