【问题标题】:Matlab: EulerSieve with Boolean vectorsMatlab:带有布尔向量的 EulerSieve
【发布时间】: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)

第二个代码有什么问题?

【问题讨论】:

    标签: matlab primes


    【解决方案1】:

    对于您的第二个函数,您的代码卡在while (K&lt;N) 循环中。 如果L1(K)1K 的值不会增加。 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
    

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多