-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution5.java
More file actions
76 lines (63 loc) · 2.62 KB
/
Copy pathSolution5.java
File metadata and controls
76 lines (63 loc) · 2.62 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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Solution5
{
public static void main(String[] args)
{
// is a composite natural number with an even number of digits,
// that can be factored into two natural numbers each with half as many digits as the original number
// and not both with trailing zeroes, where the two factors contain precisely all the digits of the original number,
// in any order, counting multiplicity. The first vampire number is 1260 = 21 × 60.
for (String arg : args) {
int N = Integer.parseInt(arg);
int numbersFound = 0;
int lastFoundNumber = 0;
int number = 1259;
while (true) {
number++;
String numberStr = String.valueOf(number);
if (numberStr.length() % 2 != 0) {
//need to be even
continue;
}
int factorial = factorial(numberStr.length());
List<Character> numberAsList = numberStr.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
for (int i = 0; i < factorial * 4; i++) {
//this is really nasty but I don't have time to implement permutations
Collections.shuffle(numberAsList);
String factor1 = toString(numberAsList.subList(0, numberAsList.size() / 2));
String factor2 = toString(numberAsList.subList(numberAsList.size() / 2, numberAsList.size()));
if (factor1.endsWith("0") & factor2.endsWith("0")) {
//both cannot have trailing zeroes
continue;
}
if (Integer.valueOf(factor1) * Integer.valueOf(factor2) == number) {
//found vampire!!
numbersFound++;
lastFoundNumber = number;
break;
}
}
if (numbersFound == N) {
System.out.println(lastFoundNumber);
break;
}
}
}
}
private static int factorial(int n) {
int factorial = 1;
for (int i=1;i<=n;i++) {
factorial*=i;
}
return factorial;
}
private static String toString(List<Character> chars) {
return chars.toString()
.substring(1, 3 * chars.size() - 1)
.replaceAll(", ", "");
}
}