diff options
| author | Anhgelus Morhtuuzh <william@herges.fr> | 2025-11-10 12:27:21 +0100 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <william@herges.fr> | 2025-11-10 12:27:21 +0100 |
| commit | 96299cbf09bdb75e4d6c6849c9c4c3ce000a6fc5 (patch) | |
| tree | 7d5f21e6c884a2cd87c619c5d97fddb4cceb7ea8 /lib/math/calc.ex | |
| parent | 7536cdbd312dff03ab10e46929dc1b072f881d01 (diff) | |
feat(parser): supports literal decimal numbers
Diffstat (limited to 'lib/math/calc.ex')
| -rw-r--r-- | lib/math/calc.ex | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/lib/math/calc.ex b/lib/math/calc.ex new file mode 100644 index 0000000..7dc5fcc --- /dev/null +++ b/lib/math/calc.ex @@ -0,0 +1,28 @@ +defmodule ElixirMathParser.Math.Calc do + alias ElixirMathParser.Math.Rational + def factorial(n), do: factorial_rec(n, 1) + defp factorial_rec(n, acc) when n > 0, do: factorial_rec(n - 1, acc * n) + defp factorial_rec(0, acc), do: acc + + def pow(value, exponent), do: pow_rec(value, exponent, Rational.new(1)) + + defp pow_rec(value, exponent, acc) when is_integer(exponent) do + case exponent do + 0 -> + acc + + _ when exponent < 0 -> + pow_rec(Rational.new(1, value), -exponent, acc) + + _ when Kernel.rem(exponent, 2) == 0 -> + pow_rec(Rational.mult(value, value), Kernel.div(exponent, 2), acc) + + _ -> + pow_rec( + Rational.mult(value, value), + Kernel.div(exponent - 1, 2), + Rational.mult(acc, value) + ) + end + end +end |
