zoukankan      html  css  js  c++  java
  • poj 2689 Prime Distance

    思想:

    用到了欧拉筛,然后对数组的内存的巧妙处理。

    推荐的博客:

    https://blog.csdn.net/Feynman1999/article/details/79533130?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

    推荐的b站:

    https://www.bilibili.com/video/av89230175?from=search&seid=1935489020745550394

    代码:

    #include<iostream>
    #include<stdio.h>
    #include<vector>
    using namespace std;
    const int maxn = (1<<16)+10;
    bool valid[maxn];
    int ans[maxn];
    bool vis[maxn<<4];
    int tot;
    void get_prime(int n){
        tot = 0;
        for(int i=2;i<=n;i++)
            valid[i] = true;
        for(int i=2;i<=n;i++){
            if(valid[i])
                ans[++tot] =i;
            for(int j=1;j<=tot&&ans[j]*i<=n;j++){
                valid[ans[j]*i] = false;
                if(i%ans[j]==0)
                    break;
            }
        }
    }
    
    int main(){
        get_prime(1<<16);
        int L,R;
        while(cin>>L>>R){
            for(int i=1;i<=(R-L+1);i++)
                vis[i] = true;
            if(L==1) vis[1] = false;
            for(int i=1;i<=tot;i++){
                for(int j=max(ans[i],(L-1)/ans[i]+1);j<=R/ans[i];j++){
                    vis[ans[i]*j-L+1] = false;
                }
            }
            int num = 0;
            for(int i=1;i<=(R-L+1);i++)
                if(vis[i]) num++;
            if(num>=2){
                vector<int>tep;
                for(int i=1;i<=(R-L+1);i++){
                    if(vis[i]) tep.push_back(L+i-1);
                }
                int ans1 = 0,ans2 = 0;
                int maxx = tep[1] - tep[0],minn = tep[1]-tep[0];
                for(int i=2;i<tep.size();i++){
                    if(tep[i]-tep[i-1]>maxx){
                        ans2 = i-1;
                        maxx = tep[i] -tep[i-1];
                    }
                    if(tep[i]-tep[i-1]<minn){
                        ans1 =i-1;
                        minn = tep[i] - tep[i-1];
                    }
                }
                cout<<tep[ans1]<<","<<tep[ans1+1]<<" are closest, "<<tep[ans2]<<","<<tep[ans2+1]<<" are most distant."<<endl;
            }
            else{
                cout<<"There are no adjacent primes."<<endl;
            }
        }
        return 0;
    }
  • 相关阅读:
    Kotlin函数之fun?function?
    Kotlin什么是top-level?
    Kotlin基础类型
    Hello,Kotlin!
    delphi 窗体自适应屏幕分辨率
    关于 Delphi 中流的使用(7) 压缩与解压缩(TCompressionStream、TDecompressionStream)
    delphi视频聊天
    两个DataGridEHToExcel
    用Delphi实现网络视频编程
    delphi Base64编码/解码及数据压缩/解压知识
  • 原文地址:https://www.cnblogs.com/lusiqi/p/12452606.html
Copyright © 2011-2022 走看看