思路解析:
举一个简单的例子来说明:
i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
pi | 1 | 3 | 2 | 13 | 12 | 11 | 10 | 9 | 8 | 7 | 6 | 5 | 4 |
观察这三组数字的特征可以发现他们都是降序排列的,且在每一组数内部pi+i都相等且都是素数,而前面刚好是后面的子问题。说白了就是拿着n在【1,n】区间内部搜索找到第一个素数之后其他的递减填入p数组中即可。
代码如下:
#include<bits/stdc++.h>
using namespace std;
#define int long long
using T = pair<int, int>;
//set<int>S;
//unordered_map<int, int>mp;
const int N = 1e6 + 10;
int a[N];
bool isprime(int x) {
if (x == 1)return false;
int i = 2;
for (; i <= sqrt(x); ++i) {
if (x % i == 0)return false;
}
return true;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int n; cin >> n;
int i;
int pos = n;
for (i = 1; i <= pos; ++i) {
if (a[i])break;
if (isprime(pos + i)) {
a[i] = pos;
pos = i - 1;
i = 0;
}
}
if (i > n)cout << -1 << endl;
else {
for (i = 1; i <= n; ++i) {
if (a[i] == 0) {
a[i] = a[i - 1] - 1;
cout << a[i] << " ";
}
else {
cout << a[i] << " ";
}
}
}
//for (i = 1; i <= n; ++i)cout << a[i] << " ";
return 0;
}