- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
97 lines (82 loc) · 2.75 KB
/
Copy pathMain.java
File metadata and controls
97 lines (82 loc) · 2.75 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
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.HashSet;
importjava.util.List;
importjava.util.Set;
/*
@author: mc-es
Problem 49
The arithmetic sequence, 1487, 4817, 8147, n which each of the terms increases by 3330, is unusual in two ways:
(i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
Answer: 296962999629
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
System.out.println(findPrimePermutations());
}
publicstaticStringfindPrimePermutations() {
List<Integer> primes = getFourDigitPrimes();
Set<Integer> primeSet = newHashSet<>(primes);
for (intprime : primes) {
Set<Integer> perms = getPermutations(prime);
List<Integer> primePerms = newArrayList<>();
for (intperm : perms) {
if (primeSet.contains(perm) && perm >= 1000) {
primePerms.add(perm);
}
}
Collections.sort(primePerms);
for (inti = 0; i < primePerms.size(); i++) {
for (intj = i + 1; j < primePerms.size(); j++) {
intdiff = primePerms.get(j) - primePerms.get(i);
intthird = primePerms.get(j) + diff;
if (primePerms.contains(third) && primePerms.get(i) != 1487) {
return"" + primePerms.get(i) + primePerms.get(j) + third;
}
}
}
}
returnnull;
}
privatestaticList<Integer> getFourDigitPrimes() {
List<Integer> primes = newArrayList<>();
for (inti = 1000; i < 10000; i++) {
if (isPrime(i)) {
primes.add(i);
}
}
returnprimes;
}
privatestaticbooleanisPrime(intn) {
if (n < 2)
returnfalse;
for (inti = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
returnfalse;
}
returntrue;
}
privatestaticSet<Integer> getPermutations(intnum) {
Set<Integer> perms = newHashSet<>();
permute(Integer.toString(num).toCharArray(), 0, perms);
returnperms;
}
privatestaticvoidpermute(char[] chars, intindex, Set<Integer> perms) {
if (index == chars.length) {
perms.add(Integer.parseInt(newString(chars)));
return;
}
for (inti = index; i < chars.length; i++) {
swap(chars, i, index);
permute(chars, index + 1, perms);
swap(chars, i, index);
}
}
privatestaticvoidswap(char[] chars, inti, intj) {
chartemp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}