问题描述
我在MATLAB中用整数数组实现了Euler的Sieve,一切运行良好:
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
个元素的索引为素数的元素中均带有1s。
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)
第二个代码有什么问题?
解决方法
对于第二个功能,您的代码陷入了while (K<N)
循环中。
如果K
为L1(K)
,则1
的值不会增加。 (L1(K)==1
时您想做什么?)
现在,我不确定您是否具有必须使用二进制文件的条件。如果没有,一个更简单的解决方案是使用您的第一个函数和数组索引:
A = EulerSieve1(N); % Get primes from 1:N
B = false(1,N); % [1,N] matrix of logical false
B(A) = true; % Set elements in B,at indices specified by vector A,as true