Four is magic: Difference between revisions
Content deleted Content added
m →{{header|REXX}}: added whitespace. |
→{{header|UNIX Shell}}: Fix bug in name translation. |
||
Line 3,272: | Line 3,272: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|Bash|4+}} |
{{works with|Bash|4+}} |
||
<lang sh># |
<lang sh>#!/usr/bin/env bash |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
# If the second parameter is passed in, it is appended to the name |
|||
# with a space between them; this is to facilitate tail recursion |
|||
name_of() { |
name_of() { |
||
⚫ | |||
⚫ | |||
# Names for numbers that fit in a bash integer |
|||
local suffix=$2 |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
[1000000000000]=trillion [1000000000000000]=quadrillion |
|||
⚫ | |||
⚫ | |||
# check for easy case first - exclude exact powers of 10 |
|||
⚫ | |||
# above 10 as we'll need to stick a "one" in front of those. |
|||
if [[ $n != *00 && -n ${names[$n]} ]]; then |
|||
⚫ | |||
return 0 |
|||
fi |
|||
⚫ | |||
# find the largest power of 10 that is smaller than n |
# find the largest power of 10 that is smaller than n |
||
local -i i=0 |
local -i i=0 |
||
Line 3,309: | Line 3,299: | ||
# if we found one, split on it and construct quotient 'name' remainder |
# if we found one, split on it and construct quotient 'name' remainder |
||
# since both quotient and remainder require recursion, we can't use |
|||
# tail-recursion for both. |
|||
if (( n >= p )); then |
if (( n >= p )); then |
||
local -i quotient=n/p |
local -i quotient=n/p |
||
Line 3,318: | Line 3,306: | ||
remname=$(name_of $remainder) |
remname=$(name_of $remainder) |
||
fi |
fi |
||
printf '%s %s\n' "$(name_of $quotient)" "${names[$p]}${remname:+ $remname}" |
|||
elif (( n > 20 )); then |
|||
⚫ | |||
# things are a little different under 100, since the multiples of |
# things are a little different under 100, since the multiples of |
||
# 10 have their own names |
# 10 have their own names |
||
Line 3,328: | Line 3,316: | ||
remname=-$(name_of $remainder) |
remname=-$(name_of $remainder) |
||
fi |
fi |
||
printf ' |
printf '%s\n' "${names[$tens]}${remname:+$remname}" |
||
⚫ | |||
⚫ | |||
fi |
fi |
||