This class decomposes an integer into a product of other integers,
which, when multiplied together give the integer originally
entered.
class Integer
def factors() (1…self).select { |n| (self % n).zero? }
end
end
puts "Enter an integer: "
int = gets.chomp.to_i.factors
puts “Factorization: #{int}”
If I enter 1234 at the prompt, for example, I get the following result:
Factorization: [1, 2, 617, 1234]
My problem is that I don’t want the number originally entered at the end
of the output. I want the output to look like this:
Factorization: [1, 2, 617]
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.
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.