码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 10140 - Prime Distance(数论)

时间:2014-06-24 17:20:30      阅读:314      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

10140 - Prime Distance

题目链接

题意:求[l,r]区间内最近和最远的素数对。

思路:素数打表,打到sqrt(Max)即可,然后利用大的表去筛素数,由于[l, r]最多100W,所以可以去遍历一遍,找出答案。注意1的情况,一开始没判断1,结果WA了

代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

#define INF 0x3f3f3f3f3f
const int N = 100005;
long long l, r, vis[N * 10], prime[N], pn = 0;

int main() {
	for (long long i = 2; i < N; i++) {
		if (vis[i]) continue;
		prime[pn++] = i;
		for (long long j = i; j < N; j += i)
			vis[j] = 1;
 	}
 	while (~scanf("%lld%lld", &l, &r)) {
 		memset(vis, 0, sizeof(vis));
 		for (long long i = 0; i < pn; i++) {
  			for (long long j = (l / prime[i] + (l % prime[i] != 0)) * prime[i]; j <= r; j += prime[i]) {
  				if (j / prime[i] != 1)
  					vis[j - l] = 1;
     		}
		}
		long long pre = -1;
		long long Max = 0, Min = INF;
		long long maxl, maxr, minl, minr, flag = 1;
		for (long long i = l; i <= r; i++) {
			if (vis[i - l] || i == 1) continue;
			if (pre != -1) {
				if (i - pre > Max) {
			 		Max = i - pre;
			 		maxl = pre; maxr = i;
    			}
    			if (i - pre < Min) {
    				Min = i - pre;
    				minl = pre; minr = i;
       			}
				flag = 0;
   			}
   			pre = i;
  		}
  		if (flag) printf("There are no adjacent primes.\n");
  		else printf("%lld,%lld are closest, %lld,%lld are most distant.\n", minl, minr, maxl, maxr);
  	}
	return 0;
}


UVA 10140 - Prime Distance(数论),布布扣,bubuko.com

UVA 10140 - Prime Distance(数论)

标签:style   class   blog   code   http   tar   

原文地址:http://blog.csdn.net/accelerator_/article/details/34093299

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!