Photo by Crissy Jarvis on Unsplash

Simplified Ancient Egyptian Multiplication with Elixir using Recursion — Part 2

Houman Kargaran

--

Glad to see you back :)

In the first article we worked through the decomposition. In this article we will try to bring it home and work on multiplication and sum.

If you remember we ended up with this:

iex(23)> AncientEgyptianMultiplication.decompose(238)            
[128, 64, 32, 8, 4, 2]
iex(24)> AncientEgyptianMultiplication.decompose(238) |> Enum.sum
238

Now we want firstly make sure that we have Enum.sum/1 been taking care of.

Another recursion should do it

iex(27)> AncientEgyptianMultiplication.sum_of([8, 64, 32, 8, 4, 2])
118

Nice! so we no longer need Enum.sum/1

Next we need the actual Multiplication.

238 × 13 = (128 + 64 + 32 + 8 + 4 + 2) × 13
= 128 × 13 + 64 × 13 + 32 × 13 + 8 × 13 + 4 × 13 + 2 × 13

This is the simple method. I thought if I use this so you can see that everything comes together by last recursion.

In order to do this we need to have everything laid out since the last piece is our trigger.

You won’t be able to use the above on its own as you can see in line 4 I am using the decomposition. So lets have everything together now:

iex(29)> AncientEgyptianMultiplication.multiply(238, 13)           
3094

That’ all folks :)

As you can see we managed to do Ancient Egyptian Multiplication mainly with Recursion in Elixir.

Hope this help!

Lastly, if you check the recursions, some of them are not Tail optimised. In my next article I will try to demonstrate how to Tail Optimise your recursion and why you should do it.

Cheers

H.

--

--