Module: Factorise

Included in:
Integer
Defined in:
lib/factorise.rb,
lib/factorise/version.rb

Constant Summary collapse

VERSION =
"0.4.0"

Instance Method Summary collapse

Instance Method Details

#factoriseObject

prime factors of a number



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/factorise.rb', line 6

def factorise
  number = self.to_s.dup.to_i
  factors = []

  primes_below = Prime.take_while { |p| p <= number / 2 }

  # keep if divisible
  primes_below.each do |p|
    until number % p != 0
      factors << p
      number = number / p
    end
  end

  # if no factors (=> num is prime) return num
  if factors.length == 0
    return [self]
  else
    return factors
  end
end

#factorisehObject

prime factors of a number as a hash



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/factorise.rb', line 29

def factoriseh
  array = self.factorise
  hash = {}

  # count each factor
  array.each do |factor|
    if hash.has_key? factor
      hash[factor] += 1
    else
      hash[factor] = 1
    end
  end

  return hash
end

#factorpairsObject

factor pairs of a number (two numbers that multiply to get the number)



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/factorise.rb', line 54

def factorpairs
  num = self.to_s.dup.to_i
  pairs = []
  factors = num.nonprime

  # include or not include middle value
  if factors.length % 2 == 0
    firsthalf = factors.first(factors.length / 2)
  else
    firsthalf = factors.first((factors.length / 2) + 1)
  end

  # get pairs
  firsthalf.each_with_index do |factor, index|
    pairs[index] = [factor, num/factor]
  end

  return pairs
end

#nonprimeObject

non prime factors of a number (doesnt exclude primes)



46
47
48
49
50
51
# File 'lib/factorise.rb', line 46

def nonprime
  num = self.to_s.dup.to_i

  # nice oneline
  return (1..num).select { |n| num % n == 0 }
end