A wrapper for the primesieve C prime number generator
C Ruby
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
ext/primesieve
lib
LICENSE
README.md
primesieve.gemspec

README.md

primesieve-ruby

Gem Version

Ruby bindings (gem wrapper) for the primesieve C++ library. Generates primes orders of magnitude faster than any pure Ruby code.

Installing

  • Get primesieve

  • Get the primesieve gem

    • gem install primesieve -or-
    • add gem 'primesieve' to your Gemfile and run bundle install

Usage

The syntax of the primesieve Ruby bindings is nearly identical to the syntax of the primesieve C++ library.

require 'primesieve'

# Generate an array with the primes inside [0, 20]
primes = Primesieve.generate_primes(0, 20)

# Generate an array with the first 10 primes starting at 0
primes = Primesieve.generate_n_primes(10, 0)

# Get the 10th prime
puts Primesieve.nth_prime(10, 0);

# Count the primes below 10**9
puts Primesieve.count_primes(0, 10**9)

Here is a list of all available functions.

Multi-threading

Counting primes and prime k-tuplets and finding the nth prime can be done in parallel using multiple threads, just use the parallel_ prefix and primesieve will use all your CPU cores.

require 'primesieve'

# Count the primes below 10**11 using all CPU cores
puts Primesieve.parallel_count_primes(0, 10**11)

# Find the 10**10th prime (starting at 0) using all CPU cores
puts Primesieve.parallel_nth_prime(10**10, 0)

How fast is it?

Ruby 2.1.3 Prime module vs. primesieve to generate the first 10,000,000 primes.

           user     system      total        real
Ruby  26.680000   3.930000  30.610000 ( 30.621654)
gem    0.290000   0.070000   0.360000 (  0.361699)