称号:

给出一个区间[L,R]求在该区间内的素数最短,最长距离。 (R < 2 * 10^9 , R - L <= 10 ^ 6)

由数论知识可得一个数的因子可在开根号内得到。

所以,我们能够打出5*10^4内得素数。然后,在用一次筛法把在[L。R]内得合数找到,则剩下的就是素数了。这里要用到离散化。把一个数 x - L 保存在数组里。由于,直接保存肯定不行。可是我们发现区间特点较小。所以。能够想到离散化。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std; typedef long long LL;
const int MAXN = 50000;
int primes[MAXN];
bool vst[MAXN];
int notPrimes[1000010];
int pos[1000010];
int top,pcnt; void init(){
top = 0;
memset(vst,0,sizeof(vst));
vst[0] = vst[1] = 1;
for(int i = 2;i < MAXN;++i)if(!vst[i]){
primes[top++] = i;
for(int j = i + i;j < MAXN;j += i) vst[j] = 1;
}
//printf("top: %d\n",top);
} void solve(int L,int R){
memset(notPrimes,0,sizeof(notPrimes)); if(L == 1) L = 2; /// 防止筛掉全部该区间的素数本身!!!!!
for(int i = 0;i < top&&(LL)primes[i]*primes[i] <= R;++i){ //筛选因子
int s = L / primes[i] + (L % primes[i] > 0); //当前素数的最小倍数达到L s = (s == 1 ? 2 : s); /// 防止筛掉全部该区间的素数本身!!!!! for(int j = s;(LL)j*primes[i] <= R;++j){
if((LL)j*primes[i] >= L) //合数
notPrimes[j*primes[i] - L] = 1; // 相当与离散化
}
} pcnt = 0;
for(int i = 0;i <= R - L;++i){
if(!notPrimes[i]){
pos[pcnt++] = i + L;
//printf("i -- > %d\n",i + L);
}
} if(pcnt < 2){
puts("There are no adjacent primes.");
} else {
int minl,minr,maxl,maxr,minv = 999999,maxv = -1;
for(int i = 1;i < pcnt;++i){
if(pos[i] - pos[i-1] > maxv){
maxv = pos[i] - pos[i-1];
maxl = pos[i-1];
maxr = pos[i];
}
if(pos[i] - pos[i-1] < minv){
minv = pos[i] - pos[i-1];
minl = pos[i-1];
minr = pos[i];
}
}
printf("%d,%d are closest, %d,%d are most distant.\n",minl,minr,maxl,maxr);
}
}
int main()
{
init();
int L,R;
while(~scanf("%d%d",&L,&R)){
solve(L,R);
}
return 0;
}

版权声明:本文博客原创文章,博客,未经同意,不得转载。

最新文章

  1. iOS-证书
  2. “用户、组或角色&#39;XXX&#39;在当前数据库中已存在”问题
  3. IOS第一天多线程-01pthread
  4. centos6.7 安装Docker
  5. jdk 与jre的区别
  6. Integer和int的详细比较(转)
  7. python threading 模块来实现多线程
  8. 计算facebook sdk需要的key hashes
  9. 【JAVA零基础入门系列】Day14 Java对象的克隆
  10. express+vue+mongodb+session 实现注册登录
  11. [转帖]Docker容器CPU、memory资源限制
  12. 用python画小王八裤(turtle库)
  13. Redis占硬盘空间
  14. yum-Remi源配置
  15. socket的相关知识理解
  16. 二叉苹果树|codevs5565|luoguP2015|树形DP|Elena
  17. Ink——一款使用React风格开发命令行界面应用(CLI App)的nodejs工具
  18. 001-读书笔记-企业IT架构转型之道-阿里巴巴中台战略思想与架构实战-第一章 阿里巴巴集团中台战略引发的思考
  19. python 线程 进程 协程 学习
  20. koa2 知识点

热门文章

  1. iOS设备定位
  2. Robotium原则的实施源代码分析
  3. 代写java程序qq:928900200
  4. 设置Windows 8.1屏幕自己主动旋转代码, Auto-rotate function code
  5. Lucene40SkipListWriter
  6. 为什么tap事件绑定在document上,而不是对象本身上
  7. Java线程Dump分析工具--jstack(转)
  8. [Servlet3.0新功能]注释替代配置文件
  9. VC档(夹)文件夹路径的经营方针和代码
  10. 【转】Directx11 SDK文档