freeCodeCamp/curriculum/challenges/chinese/10-coding-interview-prep/rosetta-code/ethiopian-multiplication.md

2.9 KiB
Raw Blame History

id title challengeType forumTopicId dashedName
599d1566a02b571412643b84 Ethiopian multiplication 5 302257 ethiopian-multiplication

--description--

Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.

Method:

  1. Take two numbers to be multiplied and write them down at the top of two columns
  2. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of 1
  3. In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows 1
  4. Examine the table produced and discard any row where the value in the left column is even
  5. Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together

For example: 17 × 34

17   34

Halving the first column:

17   34
8
4
2
1

Doubling the second column:

17   34
8    68
4   136
2   272
1   544

Strike-out rows whose first cell is even:

17   34
8    68
4   136
2   272
1   544

Sum the remaining numbers in the right-hand column:

17   34
8    --
4   ---
2   ---
1   544
   ====
    578

So 17 multiplied by 34, by the Ethiopian method is 578.

--instructions--

The task is to define three named functions/methods/procedures/subroutines:

  1. one to halve an integer,
  2. one to double an integer, and
  3. one to state if an integer is even

Use these functions to create a function that does Ethiopian multiplication.

--hints--

eth_mult should be a function.

assert(typeof eth_mult === 'function');

eth_mult(17,34) should return 578.

assert.equal(eth_mult(17, 34), 578);

eth_mult(23,46) should return 1058.

assert.equal(eth_mult(23, 46), 1058);

eth_mult(12,27) should return 324.

assert.equal(eth_mult(12, 27), 324);

eth_mult(56,98) should return 5488.

assert.equal(eth_mult(56, 98), 5488);

eth_mult(63,74) should return 4662.

assert.equal(eth_mult(63, 74), 4662);

--seed--

--seed-contents--

function eth_mult(a, b) {

}

--solutions--

function eth_mult(a, b) {
  let sum = 0; a = [a]; b = [b];

  let half = a => a / 2,
    double = a => a * 2,
    is_even = a => a % 2 == 0;

  while (a[0] !== 1) {
    a.unshift(Math.floor(half(a[0])));
    b.unshift(double(b[0]));
  }

  for (let i = a.length - 1; i > 0; i -= 1) {
    if (!is_even(a[i])) {
      sum += b[i];
    }
  }
  return sum + b[0];
}