首页 > 其他 > 详细

质数距离

时间:2021-07-19 00:29:27      阅读:17      评论:0      收藏:0      [点我收藏+]

质数距离

本题提供了一种解决大数(1e8以上)区间中质数的方法.

对于\(x\in[L,R]\), \(x是合数\Longleftrightarrow 存在p\le50000且p\mid x,p<x\)

思路 :

  1. 先求出1~500000中质因子.
  2. 对于1~500000中的每个质因子p, 将[L,R]中所有p的倍数筛去(至少2倍).
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define VIT vector<int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1e6 + 7; 
int p[N], cnt;
bool st[N];

void init() {
    for (int i = 2; i < N; ++i) {
        if (!st[i]) p[cnt++] = i;
        for (int j = 0; p[j] * i < N; ++j) {
            st[p[j] * i] = true;
            if (i % p[j] == 0) break;
        }
    }
}

int main() {
    //freopen("in.txt", "r", stdin);
    //IO;
    init();
    int l, r;
    while (cin >> l >> r) {
        memset(st, 0, sizeof st);
        for (int i = 0; i < cnt; ++i) { 
            ll t = p[i];
            for (ll j = max(t * 2, (l + t - 1) / t * t); j <= r; j += t)
                st[j - l] = 1;
        }
        
        vector<int> v;
        for (int i = 0; i <= r - l; ++i) 
            if (!st[i] && i + l >= 2) v.pb(i + l);

        //for (int i = 0; i < v.size(); ++i) cout << v[i] << ‘ ‘;
        //cout << ‘\n‘;

        if (v.size() <= 1) printf("There are no adjacent primes.\n");
        else {
            int mi = inf, mx = 0, ans1, ans2;
            for (int i = 1; i < v.size(); ++i) {
                int t = v[i] - v[i - 1];
                if (t < mi) {
                    mi = t;
                    ans1 = i; 
                }
                if (t > mx) {
                    mx = t;
                    ans2 = i;
                }
            }
            printf("%d,%d are closest, %d,%d are most distant.\n", v[ans1 - 1], v[ans1], v[ans2 - 1], v[ans2]);
        }
    }
    return 0;
}

质数距离

原文:https://www.cnblogs.com/phr2000/p/15028055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!