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.

#palindrome? ⇒ Boolean
Returns true if the Integer is a palindrome (meaning its digits are the same forward and backward).

#pandigital? ⇒ Boolean
Returns true if the integer is pandigital.

#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.
23 24 25 26 27 
# File 'lib/magician/integer.rb', line 23 def factorial return 1 if zero? downto(1).reduce :* 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).
12 13 14 15 16 
# File 'lib/magician/integer.rb', line 12 def factors raise ArgumentError, '0 has infinite factors, so the Array of its factors cannot be computed in finite time' if zero? 1.upto(abs/2).select { i abs.divisible? i } << abs end 
#palindrome? ⇒ Boolean
Returns true if the Integer is a palindrome (meaning its digits are the same forward and backward).
53 54 55 
# File 'lib/magician/integer.rb', line 53 def palindrome? to_s.split(//).palindrome? end 
#pandigital? ⇒ Boolean
Returns true if the integer is pandigital. That is, the integer contains each of the digits from 1 to 9 exactly once.
45 46 47 
# File 'lib/magician/integer.rb', line 45 def pandigital? to_s.split(//).sort.join == '123456789' 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.
35 36 37 38 39 
# File 'lib/magician/integer.rb', line 35 def prime? return false if self <= 1 2.upto(Math.sqrt self).none? { i divisible? i } end 