Created
March 19, 2020 23:01
-
-
Save houmanka/bc4d960bdb1b8678e63b8d27fdbbe61c to your computer and use it in GitHub Desktop.
AEM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AncientEgyptianMultiplication do | |
require Integer | |
def decompose(n) do | |
power_ready = case Integer.is_odd(n) do | |
true -> n - 1 | |
false -> n | |
end | |
greatest_pow_2 = of(power_ready, []) |> count_of | |
decompose(n, greatest_pow_2, []) | |
end | |
def decompose(n, _, state) when n == 1, do: state ++ [n] | |
def decompose(n, _, state) when n <= 0, do: state | |
def decompose(n, closest_number, state) do | |
pow_2 = :math.pow(2, closest_number) |> Kernel.trunc | |
case pow_2 <= n do | |
true -> | |
n = (n - pow_2) | |
state = state ++ [pow_2] | |
decompose(n, closest_number - 1, state) | |
false -> | |
decompose(n, closest_number - 1, state) | |
end | |
end | |
defp of(n, state) when n <= 1, do: state | |
defp of(n, state) do | |
n = (n / 2) | |
|> Kernel.trunc | |
state = state ++ [n] | |
of(n, state) | |
end | |
def multiply(first, second) do | |
decomposed = decompose(first) | |
multiply(decomposed, second, []) | |
end | |
def multiply([], _, state), do: sum_of(state) | |
# 128 × 13 + 64 × 13 + 32 × 13 + 8 × 13 + 4 × 13 + 2 × 13 | |
def multiply([head | tail], second, state) do | |
state = state ++ [head * second] | |
multiply(tail, second, state) | |
end | |
defp sum_of([head | tail]) do | |
sum_of(tail, head) | |
end | |
defp sum_of([], state), do: state | |
defp sum_of([head | tail], state) do | |
sum_of(tail, state + head) | |
end | |
defp count_of([_head | tail]) do | |
count_of(tail, 1) | |
end | |
defp count_of([], state), do: state | |
defp count_of([_head | tail], state) do | |
count_of(tail, state + 1) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment