Hi Folks.
Came across this question on Codewars, and I wasn’t even able to submit with a “this took longer than 12sec to run” for their submission test suite.
In mathematics, a Diophantine equation is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied.
In this kata we want to find all integers
x, y
(x >= 0, y >= 0
) solutions of a diophantine equation of the form:x^2 - 4 * y^2 = n
(where the unknowns are
x
andy
, andn
is a given positive number) in decreasing order of the positive xi.If there is no solution return
[]
or"[]" or ""
. (See “RUN SAMPLE TESTS” for examples of returns).
Here is my current solution using some horribly written recursion D:. It is MUCH more performant than my first few renditions, but still no where near fast enough to submit to codewars apparently. Can anyone help me understand why this is still slow?
defmodule Dioph do
@eq "x2 - 4 * y2 = n"
@eq_terms_of_x "x = sqrt(n + (4 * y^2))"
@eq_terms_of_y " y = sqrt((-1 * (n - x^2))/4)"
def solve(n) do
k = round(n/2 + 1)
equation(n, k, []) |> Enum.reverse
end
def equation(_, 0, acc), do: acc
def equation(n, val, acc) do
x = val
right_side = (-1 * (n - :math.pow(x, 2))/4)
y = if right_side < 0.00, do: -1.00, else: :math.sqrt(right_side)
if is_valid_result?({x, y}), do: equation(n, val-1, [{round(x), round(y)}| acc]), else: equation(n, val-1, acc)
end
def is_valid_result?({x, y}) do
round(x) == x && x != -1 && round(y) == y && y != -1
end
end