Ethiopian Multiplication

Little Anny has a lemonade shop, but she wants to go online and sell the lemonade on her own website. At school she learned how to multiply two numbers and she needs you to implement it now. It's a rather curious way of multiplying numbers, so listen up!

To arrive at the final price, you need to double the price and halve the amount of lemonades. Each time you do that sometimes the price turns into funny objects like rubber ducks, tiny pianos, and even a miniature unicorn! This process repeats until there's only one lemonade left. When that happens, the multiplication is done and the final price is calculated.

Anny's Lemonade Shop

Add link to the standalone example. Note with a badge that this example is part of a web development lecture.

a:
b:
result:
Box
Box
Box
Box

Asking the right questions

'How to cut rubber ducks in half' probably is not a question that would be helpful. Don't be afraid to ask obvious questions.

Mental tools

  • Name
    while
    Type
    loop
    Description

    Repeat doubling and halving until you're done.

  • Name
    modulo
    Type
    operator
    Description

    Determine the remainder of a given number.

  • Name
    flooring
    Type
    math
    Description

    After halving, possibly remaining fractions are dropped.

  • Name
    if
    Type
    conditional
    Description

    Check whether a number is odd or even.


Solution

SOLUTION
Ethiopian Multiplication
function multiply(a, b) {
  let result = a % 2 != 0 ? b : 0
  while (a > 1) {
    a = Math.floor(a / 2)
    b = b * 2
    if (a % 2 != 0) result += b
  }
  return result
}

Harder, Better, Faster

Improve on the algorithm by making it faster or have it consume less memory, or some other kind of trick that makes the solution more awesome.

Check out these coding problems. They are similar in some respect.

  • this
  • that

i like to coach, from observation i coached all kinds of people, pupils in math and language, students in math and coding it's about access to people we need more people in tech, but bootcamps don't tap into accessing non-technical people

Was this page helpful?