Ethiopian multiplication: Difference between revisions
Content added Content deleted
(→{{header|Bash}}: Removed as there is a bash version under Unix/Shell) |
(→{{header|UNIX Shell}}: Retrieved formerly-Bash example.) |
||
Line 2,133: | Line 2,133: | ||
echo $(ethiopicmult 17 34)</lang> |
echo $(ethiopicmult 17 34)</lang> |
||
While breaking if the --posix flag is passed to bash, the following is a slight alternative to the above that forces variable scoping and avoids the use of the *, /, and % operators. |
|||
{{works with|bash}} |
|||
<lang bash>halve() { |
|||
echo -n $(( $1 >> 1 )) |
|||
} |
|||
double() { |
|||
echo -n $(( $1 << 1 )) |
|||
} |
|||
is_even() { |
|||
[ $(( $1 & 1 )) -eq 0 ] |
|||
} |
|||
multiply() { |
|||
local plier=$1 |
|||
local plicand=$2 |
|||
local result=0 |
|||
while [ $plier -gt 0 ] |
|||
do |
|||
! is_even $plier && (( result += plicand )) |
|||
plier=$( halve $plier ) |
|||
plicand=$( double $plicand ) |
|||
done |
|||
echo -n $result |
|||
} |
|||
echo $( multiply 17 34 )</lang> |
|||
=={{header|Ursala}}== |
=={{header|Ursala}}== |