The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
太暴力了不忍心贴代码了(╯‵□′)╯︵┻━┻
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
bool isp[100000000];
int prime[1500];
bool isPrime(int n)
{
for (int i = 2; i*i < n; i++)
{
if (n%i == 0)
return false;
}
return true;
}
int cnt;
void prim()
{
int count = 0;
for (int i = 2; i < 100000000; i++)
{
if (isPrime(i))
{
isp[i] = 1;
if (i<10000)
prime[count++] = i;
}
}
cnt = count;
}
bool check(int a, int b, int c, int d, int e)
{
int num[5] = { a, b, c, d, e };
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (i == j)
continue;
int tp1 = num[i];
int tp2 = num[j];
while (tp2)
{
tp1 *= 10;
tp2 /= 10;
}
tp1 += num[j];
if (isp[tp1] == 0)
return false;
}
}
return true;
}
bool twocheck(int a, int b)
{
int tp1 = a;
int tp2 = b;
while (tp2)
{
tp1 *= 10;
tp2 /= 10;
}
tp1 += b;
if (isp[tp1])
return true;
return false;
}
int main()
{
memset(isp, 0, sizeof(isp));
prim();
int res = 0;
int flag = 0;
for (int a = 0; a < cnt; a++)
{
if (flag == 1)
break;
for (int b = a + 1; b < cnt; b++)
{
if (!twocheck(prime[a], prime[b]) || !twocheck(prime[b], prime[a]))
continue;
if (flag == 1)
break;
for (int c = b + 1; c < cnt; c++)
{
if (!twocheck(prime[c], prime[b]) || !twocheck(prime[b], prime[c]) || !twocheck(prime[a], prime[c]) || !twocheck(prime[c], prime[a]))
continue;
if (flag == 1)
break;
for (int d = c + 1; d < cnt; d++)
{
if (!twocheck(prime[d], prime[b]) || !twocheck(prime[b], prime[d]) || !twocheck(prime[a], prime[d]) || !twocheck(prime[d], prime[a])
|| !twocheck(prime[c], prime[d]) || !twocheck(prime[d], prime[c]))
continue;
if (flag == 1)
break;
for (int e = d + 1; e < cnt; e++)
{
if (check(prime[a], prime[b], prime[c], prime[d], prime[e]))
{
res = prime[a] + prime[b] + prime[c] + prime[d] + prime[e];
cout << res << endl;
flag = 1;
break;
}
}
}
}
}
}
system("pause");
return 0;
}