- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
75 lines (62 loc) · 2.14 KB
/
Copy pathMain.java
File metadata and controls
75 lines (62 loc) · 2.14 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
importjava.util.*;
/*
@author: mc-es
Problem 41
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
Answer: 7652413
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
System.out.println(largestPandigitalPrime());
}
publicstaticbooleanisPrime(intn) {
if (n <= 1) returnfalse;
if (n == 2) returntrue;
if (n % 2 == 0) returnfalse;
for (inti = 3; i * i <= n; i += 2) {
if (n % i == 0) returnfalse;
}
returntrue;
}
publicstaticintlargestPandigitalPrime() {
for (intn = 9; n >= 1; n--) {
Stringdigits = "";
for (inti = 1; i <= n; i++) {
digits += i;
}
Set<String> pandigitalNumbers = newHashSet<>();
permute(digits, 0, digits.length() - 1, pandigitalNumbers);
List<Integer> pandigitalList = newArrayList<>();
for (StringnumStr : pandigitalNumbers) {
pandigitalList.add(Integer.parseInt(numStr));
}
Collections.sort(pandigitalList, Collections.reverseOrder());
for (intnum : pandigitalList) {
if (isPrime(num)) {
returnnum;
}
}
}
return -1;
}
publicstaticvoidpermute(Stringstr, intleft, intright, Set<String> result) {
if (left == right) {
result.add(str);
} else {
for (inti = left; i <= right; i++) {
str = swap(str, left, i);
permute(str, left + 1, right, result);
str = swap(str, left, i);
}
}
}
publicstaticStringswap(Stringstr, inti, intj) {
char[] charArray = str.toCharArray();
chartemp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
returnnewString(charArray);
}
}