how to calculate prime numebrs in ruby

To calculate prime numbers in Ruby, we can write a simple algorithm that iterates through a range of numbers and checks whether each number is divisible by any number other than 1 and itself. If a number is not divisible by any other number, it is a prime number.

Here is a possible implementation of this algorithm:

main.rb
require 'prime'

def calculate_primes(max)
  primes = []
  (2..max).each do |num|
    primes << num if num.prime?
  end
  primes
end

# example usage
puts calculate_primes(50).inspect
# output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
251 chars
14 lines

In this implementation, we use the prime? method from the Prime library to check whether a number is prime. The calculate_primes method takes a maximum number as input and returns an array of all prime numbers from 2 up to that maximum number.

Note that there are more efficient algorithms for calculating prime numbers, but this implementation should work for small to medium-sized ranges.

gistlibby LogSnag