Problem 118
Using all of the digits 1 through 9 and concatenating them freely to form decimal integers, different sets can be formed. Interestingly with the set {2,5,47,89,631}, all of the elements belonging to it are prime.
How many distinct sets containing each of the digits one through nine exactly once contain only prime elements?
C++:
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 9;
int val[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
long ans;
bool isprime(long n)
{
if(n == 1)
return false;
if(n == 2)
return true;
if(n % 2 == 0)
return false;
long end = sqrt(n);
for(long i=3; i<=end; i+=2)
if(n % i == 0)
return false;
return true;
}
void primeset(int pos, long long leftval)
{
if(pos >= N) {
ans++;
return;
}
long long value = 0;
while(pos < N) {
value *= 10;
value += val[pos++];
if(isprime(value) && value >= leftval)
primeset(pos, value);
}
}
int main()
{
ans = 0;
for(;;) {
primeset(0, 0);
if(!next_permutation(val, val + N))
break;
}
cout << ans << endl;
return 0;
}