Class: Integer
- Inherits:
-
Object
- Object
- Integer
- Defined in:
- lib/magician/integer.rb
Overview
Magician’s extensions to the Integer class.
Instance Method Summary collapse
-
#factorial ⇒ Integer
Gets the factorial of the integer, which is equivalent to the product of all integers from 1 to the integer (inclusive).
-
#factors ⇒ Array
Gets all of the factors of the current integer.
-
#prime? ⇒ Boolean
Returns true if the integer is prime (that is, if it is not divisible by any integer between 1 and the integer itself, exclusive).
Instance Method Details
#factorial ⇒ Integer
Gets the factorial of the integer, which is equivalent to the product of all integers from 1 to the integer (inclusive). When the integer is 0, it is equivalent to 1.
36 37 38 39 |
# File 'lib/magician/integer.rb', line 36 def factorial return 1 if self == 0 (1..self).inject(:*) end |
#factors ⇒ Array
Gets all of the factors of the current integer. If the current integer is negative, it will be treated as if it were positive (so the results will never contain negative integers). Returns nil if the integer is 0.
order, including 1 and the integer itself)
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/magician/integer.rb', line 10 def factors return nil if self == 0 return [1] if abs == 1 #first half factors = [] for i in 1..abs if abs % i == 0 if i < abs/i factors << i else break end end end #second half factors_old = factors.dup until factors_old.length == 0 factors << abs/factors_old.pop end factors end |
#prime? ⇒ Boolean
Returns true if the integer is prime (that is, if it is not divisible by any integer between 1 and the integer itself, exclusive). 0 and 1 are not prime numbers, though 2 is prime. Negative numbers are never considered prime in this implementation.
47 48 49 50 51 52 53 |
# File 'lib/magician/integer.rb', line 47 def prime? return false if self <= 1 for i in 2..Math.sqrt(self) return false if self % i == 0 end true end |