-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem41.cpp
68 lines (57 loc) · 1.15 KB
/
problem41.cpp
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
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <map>
using namespace std;
#define N 987654321
vector<int> vnum;
map<int,bool> used;
int max_panprime(0);
vector<bool> isPrime(N+1,true);
void sieve()
{
isPrime[1] = true;
isPrime[2] = true;
for (int i = 2; i <= sqrt(N);i++){
for (int j = i*i; j<=N;j+=i){
isPrime[j] = false;
}
}
}
int decode(vector<int> const& vnum){
auto p = pow(10,vnum.size()-1);
int acc = 0;
for (auto d:vnum){
acc+= d*p;
p/=10;
}
return acc;
}
void checkPandigital(int targetNumDigits)
{
if (vnum.size()==targetNumDigits){
auto num = decode(vnum);
if (isPrime[num] && num > max_panprime){
max_panprime = num;
}
}
for (int i = 1;i<=targetNumDigits;i++){
if (!used[i]){
used[i] = true;
vnum.push_back(i);
checkPandigital(targetNumDigits);
vnum.pop_back();
used[i] = false;
}
}
}
// 123456789
// 100000000
int main()
{
sieve();
checkPandigital(7);
cout<<max_panprime<<endl;
return 0;
}