Class: EbisuConnection::GreatestCommonDivisor

Inherits:
Object
  • Object
show all
Defined in:
lib/ebisu_connection/greatest_common_divisor.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(set) ⇒ GreatestCommonDivisor

Returns a new instance of GreatestCommonDivisor.



9
10
11
# File 'lib/ebisu_connection/greatest_common_divisor.rb', line 9

def initialize(set)
  @set = set.sort.uniq
end

Class Method Details

.calc(set) ⇒ Object



4
5
6
# File 'lib/ebisu_connection/greatest_common_divisor.rb', line 4

def calc(set)
  self.new(set).calc
end

Instance Method Details

#calcObject



13
14
15
16
17
18
19
20
21
22
# File 'lib/ebisu_connection/greatest_common_divisor.rb', line 13

def calc
  n = @set.shift
  return n if n == 1 || @set.empty?

  while !@set.empty?
    m = @set.shift
    n = gcd_euclid(m, n)
  end
  n
end

#gcd_euclid(m, n) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/ebisu_connection/greatest_common_divisor.rb', line 24

def gcd_euclid(m, n)
  m, n = n, m if m < n
  while n != 0
    work = m % n
    m = n
    n = work
  end
  m
end