52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/crypto_toolchain/extensions/integer_extensions.rb', line 52
def root(n, round: :down)
raise ArgumentError.new("round must be in [#{ROUNDING.join(', ')}]") unless ROUNDING.include?(round)
raise ArgumentError.new("Can't be called on 0") if self == 0
x = self
loop do
prev = x
x = ((n - 1) * prev) + (self / (prev ** (n - 1)))
x /= n
break if (prev - x) <= 0
end
if x**n == self
x
else
case round
when :up
x+1
when :down
x
when :none
raise ArgumentError.new("#{self} has no #{n}th root")
end
end
end
|