Skip to content

small code improvement #3

@dsnz

Description

@dsnz

Hi,

I was trying to understand this algorithm and implement it in python. In the process I have to propose

  • a small code improvement where the code part
  while #P < N do
    repeat
      x = x + 2
      if x >= limit then
        Q[#Q+1], limit = limit, P[#Q+2]^2
      end
    until is_prime(x)
    P[#P+1] = x
  end

can be replaced by just

  while #P < N do
    x = x + 2
    if x >= limit then
      Q[#Q+1], limit = limit, P[#Q+2]^2
    end
    if is_prime(x) then
      P[#P+1] = x
    end
  end

which eliminates one extra needless loop and is easier to understand

  • the blog statement
    "The largest prime we need to check is the one before the limit prime q, with index P[q_idx-1]. Q only stores values up to that index"
    is not so helpful and should be changed to the following or similar
The largest prime we need to check is the one before the limit prime q
whose square is kept in 'limit' variable
and entered as last entry in table Q when the 'limit' is exceeded
(because only then will this last Q entry have to be considered in the is_prime logic
and then this entry is updated as necessary again by the is_prime logic)
so table Q has always one less entry than table P
by the time table Q has to be extended by one entry it is certain that
table P will have already been extended too by the next prime

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions