How to resolve the algorithm Ethiopian multiplication step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Ethiopian multiplication step by step in the D programming language

Table of Contents

Problem Statement

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

Method:

For example:   17 × 34 Halving the first column: Doubling the second column: Strike-out rows whose first cell is even: Sum the remaining numbers in the right-hand column: So 17 multiplied by 34, by the Ethiopian method is 578.

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

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

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Ethiopian multiplication step by step in the D programming language

Source code in the d programming language

int ethiopian(int n1, int n2) pure nothrow @nogc
in {
    assert(n1 >= 0, "Multiplier can't be negative");
} body {
    static enum doubleNum = (in int n) pure nothrow @nogc => n * 2;
    static enum halveNum = (in int n) pure nothrow @nogc => n / 2;
    static enum isEven = (in int n) pure nothrow @nogc => !(n & 1);

    int result;
    while (n1 >= 1) {
        if (!isEven(n1))
            result += n2;
        n1 = halveNum(n1);
        n2 = doubleNum(n2);
    }

    return result;
} unittest {
    assert(ethiopian(77, 54) == 77 * 54);
    assert(ethiopian(8, 923) == 8 * 923);
    assert(ethiopian(64, -4) == 64 * -4);
}

void main() {
    import std.stdio;

    writeln("17 ethiopian 34 is ", ethiopian(17, 34));
}


  

You may also check:How to resolve the algorithm MD4 step by step in the Tcl programming language
You may also check:How to resolve the algorithm A+B step by step in the Insitux programming language
You may also check:How to resolve the algorithm Sorting algorithms/Comb sort step by step in the Forth programming language
You may also check:How to resolve the algorithm Classes step by step in the Nanoquery programming language
You may also check:How to resolve the algorithm Topswops step by step in the Elixir programming language