Module: MissingMath::Integer

Included in:
Integer
Defined in:
lib/missing_math.rb

Overview

Methods that apply to integers

Instance Method Summary collapse

Instance Method Details

#factorialObject

Calculates an integer’s factorial



135
136
137
138
# File 'lib/missing_math.rb', line 135

def factorial
  throw "Not an Integer" if !self.is_i?
  self.downto(1).reduce(:*)
end

#factors(include_one = true) ⇒ Object

Returns an array of an integer’s factors

Parameters:

  • boolean

    include_one To exclude the number 1 from the output, set to false



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/missing_math.rb', line 142

def factors(include_one=true)
  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

#prime?Boolean

Returns boolean true|false if integer is prime

Returns:

  • (Boolean)


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/missing_math.rb', line 117

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_factorsObject

Returns an array of the integer’s prime factors



159
160
161
162
163
164
# File 'lib/missing_math.rb', line 159

def prime_factors
  ceil = (self / 2).floor
  primes = MissingMath.esieve(ceil)
  factors = primes.collect { |i| self % i == 0 }
  return factors
end