北航计算机夏令营机试(?)质数等差序列
题意:
思路:
- 首先,枚举等差序列的间隔,即 等差序列的差;
- 然后,枚举 目标等差序列 % 间隔 这个余数。比如对于间隔 = 2,先考虑 余数=0(如 2 4 6),再考虑 余数=1(如 3 5 7)。
- 最后,捞出质数表里 数值 % 间隔 = 目标余数 的数,试图把它们连成序列。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9+7;
int a, b, prime[5000], cnt=0;
void gene_prime(){
bool is_not_p[20000];
memset(is_not_p, false, sizeof(is_not_p)); // everyone is
for(int i=2; i<10000; ++i){
if(is_not_p[i]) continue;
prime[cnt++] = i;
// cout<<i<<" is prime\n";
for(int j=2*i; j<20000; j+=i) is_not_p[j]=true;
}
}
int main(){
ios::sync_with_stdio(false);
gene_prime();
// for(int i=0; i<cnt; ++i) cout<<prime[i]<<" "; cout<<endl;
cin>>a>>b;
int left = lower_bound(prime, prime+cnt, a) - prime;
int right = lower_bound(prime, prime+cnt, b) - prime;
if(prime[right]>b) --right;
bool solved[20000]; vector<int> result;
for(int spa=2; spa<=(b-a)/3; ++spa){
memset(solved, false, sizeof(solved));
for(int start=left; start < right; ++start){
if(solved[prime[start]%spa]) continue;
solved[prime[start]%spa] = true;
result.clear();
for(int i=start; i<=right; ++i){
if(prime[i] % spa == prime[start] % spa){
if((!result.empty()) &&
prime[i]-result[result.size()-1]==spa){ // connect
result.push_back(prime[i]);
}
else { // print
if(result.size()>2){
for(auto xx : result) cout<<xx<<" ";
cout<<endl;
}
result.clear(); result.push_back(prime[i]);
}
}
}
}
}
}
执行结果(跟 前文参考博客 不太一样):
141 400
167 173 179
227 233 239
251 257 263 269
347 353 359
151 157 163
271 277 283
367 373 379
257 269 281 293
199 211 223
167 179 191
227 239 251 263
193 211 229
163 181 199
233 251 269
149 173 197
269 293 317
283 307 331
233 257 281
151 181 211 241 271
163 193 223
167 197 227 257
233 263 293
157 193 229
149 191 233
157 199 241 283
229 271 313
181 229 277
173 227 281

浙公网安备 33010602011771号