Happy numbers: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
(→{{header|UNIX Shell}}: Make solution compatible with ksh and zsh.) |
||
Line 6,713: | Line 6,713: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|Bourne Again SHell}} |
{{works with|Bourne Again SHell}} |
||
{{works with|Korn Shell}} |
|||
⚫ | |||
{{works with|Z Shell}} |
|||
function sum_of_square_digits |
|||
⚫ | |||
{ |
|||
typeset -i n=$1 sum=0 d |
|||
while (( n )); do |
while (( n )); do |
||
(( d=n%10, sum+=d*d, n=n/10 )) |
|||
let sum+=d*d |
|||
let n=n/10 |
|||
done |
done |
||
printf '%d\n' "$sum" |
|||
} |
} |
||
function is_happy |
function is_happy { |
||
typeset -i n=$1 |
|||
{ |
|||
typeset -a seen=() |
|||
local seen=() |
|||
while (( n != 1 )); do |
while (( n != 1 )); do |
||
if [ -n |
if [[ -n ${seen[$n]} ]]; then |
||
return 1 |
return 1 |
||
fi |
fi |
||
seen[n]=1 |
seen[$n]=1 |
||
(( n=$(sum_of_square_digits "$n") )) |
|||
done |
done |
||
return 0 |
return 0 |
||
} |
} |
||
function first_n_happy |
function first_n_happy { |
||
⚫ | |||
{ |
|||
for (( n=1; count; n+=1 )); do |
|||
⚫ | |||
local -i n |
|||
printf '%d\n' "$n" |
|||
(( count -= 1 )) |
|||
⚫ | |||
fi |
|||
⚫ | |||
fi |
|||
done |
done |
||
return 0 |
return 0 |
||
} |
} |
||
first_n_happy 8</ |
first_n_happy 8</pre> |
||
Output:<pre>1 |
|||
7 |
|||
10 |
|||
13 |
|||
19 |
|||
23 |
|||
28 |
|||
31</pre> |
|||
=={{header|Ursala}}== |
=={{header|Ursala}}== |