Browse | Submit A New Snippet | Create A Package

 

Prime numbers

Type:
Function
Category:
Math Functions
License:
GNU General Public License
Language:
Ruby
 
Description:
Extends the Fixnum class with a "primes" method. `100.primes` will return all the prime numbers between 1 and 100.

Versions Of This Snippet::

Robert Olson
Snippet ID Download Version Date Posted Author Delete
3312.02008-01-09 22:38Robert Olson
Changes since last version::
Must faster method of generating prime numbers up to a high range. This is a modified version of some code I found on the Internet (I don't remember where).

This works the same way as the original code.
2191.02007-05-02 20:27Michael Behan

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :2.0

class Fixnum
  def primes
    prev = []
    (2..self).select do |x|
      max_p = Math.sqrt(x).truncate
      if !prev.find { |y| y <= max_p ? x % y == 0 : break }
        prev << x
      end
    end
  end
end
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..