【发布时间】:2020-09-17 04:06:19
【问题描述】:
我在 MATLAB 中使用整数数组实现了欧拉筛,一切正常:
function [L] = EulerSieve1(N)
%This function allows to find all prime numbers until N using Euler's
%sieve algorithm
L=2:N;
P=2;
i=1;
while (P^2)<=N
L1=L;
if L(i)>=P && L(i)<=N/P
L1(i)=L(i);
i=i+1;
end
L2=P*L1;
L=setdiff(L,L2);
P=P+1;
end
end
现在,我想使用布尔向量来实现该算法,以便输出是一个布尔向量,其中包含N 元素,其中索引为素数的元素中的元素为 1。
function [L] = EulerSieve2(N)
%This function allows to find all prime numbers until N using Euler's
%sieve algorithm and returns the array with 1s for all indices with prime
%values and 0s for others
L=logical(1:N);
P=2;
I=2;
K=2;
while (P^2)<=N
L1=L;
L2=L;
if I>=P && I<=N/P
L1(I)=0;
I=I+1;
end
while K<N
if L1(K)==0
L2(K*P)=0;
K=K+1;
end
end
L=L2;
P=P+1;
end
L(1)=0;
end
此时函数中断:
(17 if L1(K)==false)
第二个代码有什么问题?
【问题讨论】: