題解/算法 {196. 质数距离}

文章讨论了一个在大范围内(不超过2^9)查找素数的问题,利用关键性质:如果一个数不是素数,那么它至少有一个质因数不大于其平方根。因此,可以只关注小于等于范围平方根的质数,筛去它们的所有倍数,从而找出素数。然而,这种方法不会筛掉0和1,需要额外处理。文章提供了一种算法实现,并指出了可能的错误情况,如计算范围的处理和倍数检查的条件等。
摘要由CSDN通过智能技术生成

Contents

Link

Solution

The problem is seemingly unsolvable (iterating all prime-numbers between [ L , R ] [L, R] [L,R] where 2 ≤ L ≤ R ≤ 2 e 9 2 \leq L \leq R \leq 2e9 2LR2e9), however, it’s vital to real the problem-content carefully, there maybe a hint ( R − l ≤ 1 e 6 R - l \leq 1e6 Rl1e6) in a corner;

--

There is an important property (a common and useful Trick) for an integer x x x:
. If x x x is not a Prime-Number, then m i n ( p i ) ≤ x min(p_i) \leq \sqrt{ x} min(pi)x (in other words, there must exist a Prime-Factors p p p of x x x such that p ∣ x    ∧    p ∈ [ 1 , x ] p | x \ \ \land \ \ p \in [1, \sqrt{x}] px    p[1,x ])

As a result, we can stand in the converse view-point, focusing on all Primes p = [ 1 , 1 e 6 ] p = [1, 1e6] p=[1,1e6] instead of x x x, then any Multiple of p p p must be not a Prime-Number;
. Note that, this method would only sieved all Non-Prime-Numbers a a a which contains a Prime-Number, that is, a = 0 / 1 a = 0/1 a=0/1 would not be sieved although they are also Non-Primes;

Finding out these Prime-Numbers in the range [ l , r ] [l, r] [l,r] where 0 ≤ l ≤ r ≤ 1 e 12 ∧ ( r − l ) ≤ 1 e 6 0 \leq l \leq r \leq 1e12 \quad \land (r-l) \leq 1e6 0lr1e12(rl)1e6; the algorithm is:

int l, r;
bool Is_prime[ r - l + 1] = true;
for( p : $(all Primes `<= \sqrt{r}`){ //< any Non-Prime in [l,r] must has a Prime which is `<= \sqrt{r}`;
	for( a : [$(all number in [l,r])]_AND_[$([k*p]_AND_[k>=2] (the multiple of `p`))]){ //< @Location-1
	//< `a` is a multiple of `p`, and also `a != p` (very important); 
		Is_prime[ a - l] = false;
	}
}
//>< note that, only a Non-Prime which has a Prime-Factor (>=2) would be sieved (set `false`); in other words, although `0,1` are also Non-Primes, they would not be sieved (you need check them specially); 
vector<> primes;
for( i : [l,r]){
	if( (i >= 2) && Is_prime[ i]){ //< @Location-0
		primes.push_back( i);
	}
}

But when you applied, it is very fallible, let’s see some mistakes:
+ If int r, then for( int i = l; i <= r; ++i) would be an error, cuz r would equals INT_MAX;
+ @Location-0, the additional i >= 2;
+ @Location-1, a a a is not the multiple of p p p in the range [ l , r ] [l,r] [l,r], you must make sure a > p a > p a>p;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值