From 96299cbf09bdb75e4d6c6849c9c4c3ce000a6fc5 Mon Sep 17 00:00:00 2001 From: Anhgelus Morhtuuzh Date: Mon, 10 Nov 2025 12:27:21 +0100 Subject: feat(parser): supports literal decimal numbers --- lib/math/calc.ex | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 lib/math/calc.ex (limited to 'lib/math/calc.ex') 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 -- cgit v1.2.3