问题描述:
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?
通过分析问题,我们知道该n位数包含从1到n的数字,我们可以从大往小找。因为1-9和1-8一定是9的倍数,我们最大的数可以从7654321往下寻找,对每个数字用hashset判断和质数判断
代码如下:
public static void main(String[] args) {
for(int i = 7654321; i > 0; i--) {
if(d(i) && p(i)) {
System.out.println(i);
break;
}
}
}
public static boolean p(int n){
HashSet set = new HashSet<Integer>();
int max = 0;
while(n > 0) {
int s = n % 10;
max = Math.max(max, s);
if(set.contains(s))
return false;
set.add(s);
n /= 10;
}
return max == set.size();
}
public static boolean d(int n){
int count = 0;
for(int i = 1; i*i <= n; i++) {
if(n % i == 0) {
count+= i;
}
}
return count == 1;
}