[UVA10140]Prime Distance

题目

题目描述

The branch of mathematics called number theory is about properties of numbers. One of the areas that has captured the interest of number theoreticians for thousands of years is the question of primality. A prime number is a number that is has no proper factors (it is only evenly divisible by 1 and itself). The first prime numbers are 2,3,5,7 but they quickly become less frequent. One of the interesting questions is how dense they are in various ranges. Adjacent primes are two numbers that are both primes, but there are no other prime numbers between the adjacent primes. For example, 2,3 are the only adjacent primes that are also adjacent numbers.
Your program is given 2 numbers: L and U (1<=L< U<=2,147,483,647), and you are to find the two adjacent primes C1 and C2 (L<=C1< C2<=U) that are closest (i.e. C2-C1 is the minimum). If there are other pairs that are the same distance apart, use the first pair. You are also to find the two adjacent primes D1 and D2 (L<=D1< D2<=U) where D1 and D2 are as distant from each other as possible (again choosing the first pair if there is a tie).
Input

给定两个整数 L,R,求闭区间 [L,R]中相邻两个质数差值最小的数对与差值最大的数对。当存在多个时,输出靠前的素数对。

输入格式

Each line of input will contain two positive integers, L and U, with L < U. The difference between L and U will not exceed 1,000,000.

输出格式

For each L and U, the output will either be the statement that there are no adjacent primes (because there are less than two primes between the two given numbers) or a line giving the two pairs of adjacent primes.

输入样例

输出样例

题解

部分内容来自李煜东所著《算法进阶指南》

暴力是不可能的,R的范围太大了。
但是我们发现,R-L的范围很小,有什么办法可以求出R-L之间的质数呢?
显然:

定理:如果n是一个合数, 那么n一定有一个不超过\(\sqrt{n}\)的素数因子
推论:任意一个合数n必定包含一个不超过\(\sqrt{n}\)的质因子

用质因数分解定理可以简单证明。
所以,我们只要用筛法求出\(2\)~\(\sqrt{R}\)之间所有的质数,对于每个质数p,把\([L,R]\)中能被p整除的数标记,即标记\(i*p\left(\Big\lceil\frac{L}{P}\Big\rceil\le\Big\lceil\frac{R}{P}\Big\rceil\right)\)为合数。
最终所有还没有被标记的数就是\(\left[L,R\right]\)中的质数。对相邻质数两两比较,找出差最大的即可。
时间复杂度为\(O\left(\sum_{质数p\le\sqrt{R}}\frac{R-L}{p}\right)=O\left(\sqrt{R}loglog\sqrt{R}+(R-L)loglogR\right)\)

代码

发表评论

电子邮件地址不会被公开。 必填项已用*标注