How to Use Ruby Prime

09/22/2021

Contents

In this article, you will learn how to use Ruby Prime.

Using Ruby Prime

Ruby Prime is a built-in module that provides a number of methods for working with prime numbers. Here are some examples of how to use Ruby Prime:

Checking if a number is prime

You can use the prime? method to check if a number is prime:

require 'prime'

puts Prime.prime?(17)  # true
puts Prime.prime?(21)  # false

Generating a list of prime numbers

You can use the each method to generate a list of prime numbers:

require 'prime'

Prime.each(20) do |prime|
  puts prime
end

This will print out all the prime numbers less than or equal to 20.

Getting the nth prime number

You can use the first method to get the first n prime numbers:

require 'prime'

puts Prime.first(5)  # [2, 3, 5, 7, 11]

Generating a range of prime numbers

You can use the take_while method to generate a range of prime numbers:

require 'prime'

primes = Prime.take_while { |p| p < 20 }

puts primes.inspect  # [2, 3, 5, 7, 11, 13, 17, 19]

This will generate all the prime numbers less than 20 and put them into an array.

Generating prime factorization

You can use the prime_division method to get the prime factorization of a number:

require 'prime'

puts Prime.prime_division(28).inspect  # [[2, 2], [7, 1]]

This will print out the prime factorization of 28, which is 2^2 * 7^1.