4
votes

I've searched every site I can imagine and am unable to determine the base algorithm that ruby 1.8 uses to create a list of primes in the Prime class under mathn. The following is a runnable version of the succ method, called 100 times (in order to find the 100th prime). Does anyone know how this works?

number_of_primes = 100

seed = 1
primes = Array.new
counts = Array.new


while primes.size < number_of_primes
  i = -1
  size = primes.size
  while i < size
    if i == -1
      seed += 1
      i += 1
    else
      while seed > counts[i]
        counts[i] += primes[i]
      end
      if seed != counts[i]
        i += 1
      else
        i = -1
      end
    end
  end
  primes.push seed
  counts.push (seed + seed)
end

puts seed

The actual code is of course: http://ruby-doc.org/stdlib-1.8.7/libdoc/mathn/rdoc/Prime.html

It doesn't look like a sieve algorithm as there is no predefined list to sift through, it's not a trial division algorithm as there are no division or modulus operations. I'm totally stumped.

1
I think the question is quite clear, not sure why you got the downvotes and the close votes. - Marc-André Lafortune
I don't mind getting downvoted if I've done something stupid/posted something unclear. It would be nice, however, if people who cast the downvotes let me know why so that I could fix it. - cycala

1 Answers

5
votes

The algorithm is based on the sieve of Eratosthenes.

seed is the integer being tested for primeness. primes is the list of primes smaller than seed and counts holds the corresponding smallest multiple that is greater than seed.

Think of counts as the list of the "next" crossed out numbers, but only one per prime, constantly updated. When finding the next largest multiple, if we get exactly seed, then it's not a prime, so it resets the outer loop (with i=-1).

Only when we've updated the list of greater multiples, without encountering exactly seed, can we deduce that seed is prime.

Here's the code slightly simplified and commented:

number_of_primes = 100

seed = 1
primes = []
counts = []

while primes.size < number_of_primes
  seed += 1
  i = 0
  while i < primes.size      # For each known prime
    while seed > counts[i]   # Update counts to hold the next multiple >= seed
      counts[i] += primes[i] # by adding the current prime enough times
    end
    if seed != counts[i]
      i += 1    # Go update next prime
    else
      i = 0     # seed is a multiple, so start over...
      seed += 1 # with the next integer
    end
  end
  # The current seed is not a multiple of any of the previously found primes, so...
  primes.push seed
  counts.push (seed + seed)
end

puts seed