Nagging (simple) problem

The range literal 1...self (like Kenichi suggested) is actually the same
as 1..self - 1. So it doesn't matter what you write. You might as well
reject "self" in the block:

class Integer
  def factors
    (1..self).select { |n| n != self and (self % n).zero? }
  end
end

···

--
Posted via http://www.ruby-forum.com/.

Jan E. wrote in post #1051119:

The range literal 1...self (like Kenichi suggested) is actually the same
as 1..self - 1. So it doesn't matter what you write. You might as well
reject "self" in the block:

class Integer
  def factors
    (1..self).select { |n| n != self and (self % n).zero? }
  end
end

Note also that there is a fairly simply optimization: use self / 2 as
end of the range. There cannot be a higher integer n which satisfies x
mod n == 0 anyway. I'd probably go a bit further and also make this
Enumerator compatible:

class Integer
  def factors
    return to_enum(:factors).to_a unless block_given?

    x = 2

    while x * 2 <= self
      yield x if self % x == 0
      x += 1
    end

    self
  end
end

Of course there are far more advanced algorithms out there to solve this
even more efficiently.

Btw, neither of the presented algorithms satisfies what OP stated:

# This class decomposes an integer into a product of other integers,
# which, when multiplied together give the integer originally
# entered.

You can easily see that from 4.factors. For that another approach has
to be taken.

Kind regards

robert

···

--
Posted via http://www.ruby-forum.com/\.