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
-
.clamp(value, min, max) ⇒ Numeric
Clamp a numeric value between a minimum and maximum.
-
.factorial(n) ⇒ Integer
Factorial of a non-negative integer (n!).
-
.fibonacci(n) ⇒ Integer
N-th Fibonacci number (0-indexed: fibonacci(0) = 0, fibonacci(1) = 1).
-
.gcd(a, b) ⇒ Integer
Greatest common divisor of two integers (Euclidean algorithm).
-
.lcm(a, b) ⇒ Integer
Least common multiple of two integers.
Class Method Details
.clamp(value, min, max) ⇒ Numeric
Clamp a numeric value between a minimum and maximum
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!)
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.
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)
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
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 |