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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Ethiopian multiplication step by step in the Tcl 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 Tcl programming language

Source code in the tcl programming language

# This is how to declare functions - the mathematical entities - as opposed to procedures
proc function {name arguments body} {
    uplevel 1 [list proc tcl::mathfunc::$name $arguments [list expr $body]]
}

function double n {$n * 2}
function halve n {$n / 2}
function even n {($n & 1) == 0}
function mult {a b} {
    $a < 1 ? 0 :
    even($a) ? [logmult STRUCK] + mult(halve($a), double($b))
	     : [logmult KEPT]   + mult(halve($a), double($b)) + $b
}

# Wrapper to set up the logging
proc ethiopianMultiply {a b {tutor false}} {
    if {$tutor} {
	set wa [expr {[string length $a]+1}]
	set wb [expr {$wa+[string length $b]-1}]
	puts stderr "Ethiopian multiplication of $a and $b"
	interp alias {} logmult {} apply {{wa wb msg} {
	    upvar 1 a a b b
	    puts stderr [format "%*d %*d %s" $wa $a $wb $b $msg]
	    return 0
	}} $wa $wb
    } else {
	proc logmult args {return 0}
    }
    return [expr {mult($a,$b)}]
}

puts "17 * 34 = [ethiopianMultiply 17 34 true]"

  

You may also check:How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the Ada programming language
You may also check:How to resolve the algorithm Arithmetic/Rational step by step in the ooRexx programming language
You may also check:How to resolve the algorithm URL decoding step by step in the Oberon-2 programming language
You may also check:How to resolve the algorithm Sorting algorithms/Sleep sort step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Symmetric difference step by step in the Ada programming language