Module: Philiprehberger::MathKit::Numeric

Defined in:
lib/philiprehberger/math_kit/numeric.rb

Overview

Numeric helpers for common integer and value operations

Class Method Summary collapse

Class Method Details

.clamp(value, min, max) ⇒ Numeric

Clamp a numeric value between a minimum and maximum

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if min is greater than max



68
69
70
71
72
73
74
75
# File 'lib/philiprehberger/math_kit/numeric.rb', line 68

def clamp(value, min, max)
  raise ArgumentError, 'min must not be greater than max' if min > max

  return min if value < min
  return max if value > max

  value
end

.factorial(n) ⇒ Integer

Factorial of a non-negative integer (n!)

Parameters:

  • n (Integer)

    a non-negative integer

Returns:

  • (Integer)

    the factorial of n

Raises:

  • (ArgumentError)

    if n is negative or not an Integer



13
14
15
16
17
18
# File 'lib/philiprehberger/math_kit/numeric.rb', line 13

def factorial(n)
  raise ArgumentError, 'factorial requires an Integer' unless n.is_a?(Integer)
  raise ArgumentError, 'factorial requires a non-negative integer' if n.negative?

  (1..n).reduce(1, :*)
end

.fibonacci(n) ⇒ Integer

N-th Fibonacci number (0-indexed: fibonacci(0) = 0, fibonacci(1) = 1)

Uses an iterative algorithm for O(n) time and O(1) space.

Parameters:

  • n (Integer)

    a non-negative index

Returns:

  • (Integer)

    the n-th Fibonacci number

Raises:

  • (ArgumentError)

    if n is negative or not an Integer



27
28
29
30
31
32
33
34
35
# File 'lib/philiprehberger/math_kit/numeric.rb', line 27

def fibonacci(n)
  raise ArgumentError, 'fibonacci requires an Integer' unless n.is_a?(Integer)
  raise ArgumentError, 'fibonacci requires a non-negative integer' if n.negative?

  a = 0
  b = 1
  n.times { a, b = b, a + b }
  a
end

.gcd(a, b) ⇒ Integer

Greatest common divisor of two integers (Euclidean algorithm)

Parameters:

  • a (Integer)

    first integer

  • b (Integer)

    second integer

Returns:

  • (Integer)

    the non-negative greatest common divisor

Raises:

  • (ArgumentError)

    if either argument is not an Integer



43
44
45
46
47
# File 'lib/philiprehberger/math_kit/numeric.rb', line 43

def gcd(a, b)
  raise ArgumentError, 'gcd requires Integer arguments' unless a.is_a?(Integer) && b.is_a?(Integer)

  a.abs.gcd(b.abs)
end

.lcm(a, b) ⇒ Integer

Least common multiple of two integers

Parameters:

  • a (Integer)

    first integer

  • b (Integer)

    second integer

Returns:

  • (Integer)

    the non-negative least common multiple (0 if either is 0)

Raises:

  • (ArgumentError)

    if either argument is not an Integer



55
56
57
58
59
# File 'lib/philiprehberger/math_kit/numeric.rb', line 55

def lcm(a, b)
  raise ArgumentError, 'lcm requires Integer arguments' unless a.is_a?(Integer) && b.is_a?(Integer)

  a.abs.lcm(b.abs)
end