module MissingMath::Integer
Methods that apply to integers
Public Instance Methods
factorial()
click to toggle source
Calculates an integer's factorial
# File lib/missing_math.rb, line 153 def factorial throw "Not an Integer" if !self.is_i? if self == 0 1 else self.downto(1).reduce(:*) end end
factors(include_one=false)
click to toggle source
Returns an array of an integer's factors @param boolean include_one Default is to exclude the number 1 from the output; to include set to false
# File lib/missing_math.rb, line 164 def factors(include_one=false) throw "Not an Integer" if !self.is_i? last = self i = include_one ? 1 : 2 a = [] while i < last if self % i == 0 last = self / i a << i a << last end i += 1 end return a.sort end
hexagon()
click to toggle source
Returns the hexagonal number
# File lib/missing_math.rb, line 201 def hexagon return self * ((2 * self) - 1) end
pentagon()
click to toggle source
Returns the pentagonal number
# File lib/missing_math.rb, line 196 def pentagon return (self * ((3 * self) - 1)) / 2 end
pentagonal?()
click to toggle source
Checks if the number is pentagonal. If true, returns the number, otherwise false
# File lib/missing_math.rb, line 217 def pentagonal? n = (Math.sqrt((24 * self) + 1) + 1) / 6 if n.floor == n.ceil return n else return false end end
prime?()
click to toggle source
Returns boolean true|false if integer is prime
# File lib/missing_math.rb, line 135 def prime? throw "Not an Integer" if !self.is_i? begin last = Math.sqrt(self).floor i = 2 while i <= last if self % i == 0 return false end i += 1 end return true rescue false end end
prime_factors(force_new=false)
click to toggle source
Returns an array of the integer's prime factors @param boolean force_new Force new module variable @esieve generation. Default uses module variable @esieve if it hasn't been set
# File lib/missing_math.rb, line 182 def prime_factors(force_new=false) ceil = (self / 2).ceil primes = MissingMath.esieve(ceil, force_new) factors = primes.collect { |i| i if self % i == 0 && i <= ceil } return factors.compact.uniq end
triangle()
click to toggle source
Returns the triangle number
# File lib/missing_math.rb, line 191 def triangle return (self * (self + 1)) / 2 end
triangular?()
click to toggle source
Checks if the number is triangular. If true, returns the number, otherwise false
# File lib/missing_math.rb, line 207 def triangular? n = (Math.sqrt((8 * self) + 1) - 1) / 2 if n.floor == n.ceil return n else return false end end