Ethiopian multiplication: Difference between revisions

→‎{{header|UNIX Shell}}: Add more shells.
(Updated D code)
(→‎{{header|UNIX Shell}}: Add more shells.)
Line 2,697:
 
=={{header|UNIX Shell}}==
Tried with ''bash --posix'', and also with Heirloom's ''sh''. Beware that ''bash --posix'' has more features than ''sh''; this script uses only ''sh'' features.
(Tried with <tt>bash --posix</tt>, so it should run in <tt>sh</tt> too)
 
{{works with|Bourne Shell}}
<lang bash>halve()
{
echo $((expr "$1" / 2 ))
}
 
double()
{
echo $((expr "$1" \* 2 ))
}
 
isevenis_even()
{
echo $((expr "$1" % 2 == 0 ))>/dev/null
}
 
Line 2,718 ⟶ 2,720:
plicand=$2
r=0
while [ "$plier" -ge 1 ]; do
if [ $(isevenis_even "$plier)" -eq|| 0r=`expr ];$r then+ "$plicand"`
plier=$(`halve "$plier)"`
r=$(( r + plicand))
plicand=$(`double "$plicand)"`
fi
plier=$(halve $plier)
plicand=$(double $plicand)
done
echo $r
}
 
echo $(ethiopicmult 17 34)</lang>
# => 578</lang>
 
While breaking if the --posix flag is passed to bash, the following isalternative ascript slight alternative toavoids the above*, that forces variable scoping/, and avoids% theoperators. useIt ofalso theuses *,local /,variables and %built-in operatorsarithmetic.
 
{{works with|bash}}
{{works with|pdksh}}
{{works with|zsh}}
 
<lang bash>halve() {
echo -n $(( $1 >>= 1 ))
}
 
double() {
echo -n $(( $1 <<= 1 ))
}
 
is_even() {
[ $(( ($1 & 1 )) -eq== 0 ]))
}
 
Line 2,752 ⟶ 2,754:
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>
# => 578</lang>
 
==={{header|C Shell}}===
<lang csh>alias halve '@ \!:1 /= 2'
alias double '@ \!:1 *= 2'
alias is_even '@ \!:1 = ! ( \!:2 % 2 )'
 
alias multiply eval \''set multiply_args=( \!*:q ) \\
@ multiply_plier = $multiply_args[2] \\
@ multiply_plicand = $multiply_args[3] \\
@ multiply_result = 0 \\
while ( $multiply_plier > 0 ) \\
is_even multiply_is_even $multiply_plier \\
if ( ! $multiply_is_even ) then \\
@ multiply_result += $multiply_plicand \\
endif \\
halve multiply_plier \\
double multiply_plicand \\
end \\
@ $multiply_args[1] = $multiply_result \\
'\'
 
multiply p 17 34
echo $p
# => 578</lang>
 
=={{header|Ursala}}==
Anonymous user