The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
用了个超级麻烦的方法做出来了,先求出质数列表,再求出全排列,再找出符合条件的数。开始的时候还把等比数列这个条件忘记了,难怪输出结果那么多。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool isPrime[10000];
int cnt = 0;
vector<int>tp;
void perm(int list[], int n, int k)
{
int temp1, temp2;
if (n == 0)
{
if (list[k] != 0)
{
int sum = 0;
for (int i = 0; i <= k; i++)
sum = sum * 10 + list[i];
if (sum >= 1000 && sum < 10000)
{
if (isPrime[sum])
{
if (find(tp.begin(), tp.end(), sum) == tp.end())
{
cnt++;
tp.push_back(sum);
}
}
}
}
}
else
{
for (int i = 0; i <= n; i++)
{
temp1 = list[i];
list[i] = list[n];
list[n] = temp1;
perm(list, n - 1, k);
temp2 = list[i];
list[i] = list[n];
list[n] = temp2;
}
}
}
bool ok(int n)
{
int a[4];
int count = 0;
int num = n;
while (n)
{
a[count++] = n % 10;
n /= 10;
}
cnt = 0;
tp.clear();
tp.push_back(num);
perm(a, 3, 3);
if (cnt >= 3)
return true;
return false;
}
int main()
{
memset(isPrime, true, sizeof(isPrime));
for (int i = 2; i <= 1010; i++)
{
if (isPrime[i])
{
for (int j = 2; j*i < 10000; j++)
{
isPrime[i*j] = false;
}
}
}
for (int i = 1000; i < 10000; i++)
{
if (isPrime[i])
{
if (ok(i))
{
int b[3];
b[0] = tp[0];
b[1] = tp[1];
b[2] = tp[2];
sort(b, b + 3);
if (b[2] - b[1] == b[1] - b[0])
cout << b[0] << b[1] << b[2] << endl;
}
}
}
system("pause");
return 0;
}