Happy numbers: Difference between revisions

Content added Content deleted
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}}
<syntaxhighlight lang="bash">#!/bin/bash
{{works with|Z Shell}}
function sum_of_square_digits
<syntaxhighlight lang="bash">function sum_of_square_digits {
{
local -i n="$1" sum=0
typeset -i n=$1 sum=0 d
while (( n )); do
while (( n )); do
local -i d=n%10
(( d=n%10, sum+=d*d, n=n/10 ))
let sum+=d*d
let n=n/10
done
done
echo "$sum"
printf '%d\n' "$sum"
}
}


function is_happy?
function is_happy {
typeset -i n=$1
{
local -i n="$1"
typeset -a seen=()
local seen=()
while (( n != 1 )); do
while (( n != 1 )); do
if [ -n "${seen[$n]}" ]; then
if [[ -n ${seen[$n]} ]]; then
return 1
return 1
fi
fi
seen[n]=1
seen[$n]=1
let n="$(sum_of_square_digits "$n")"
(( n=$(sum_of_square_digits "$n") ))
done
done
return 0
return 0
}
}


function first_n_happy
function first_n_happy {
typeset -i count=$1 n
{
local -i count="$1"
for (( n=1; count; n+=1 )); do
if is_happy "$n"; then
local -i n
printf '%d\n' "$n"
for (( n=0; count; n+=1 )); do
(( count -= 1 ))
if is_happy? "$n"; then
echo "$n"
fi
let count-=1
fi
done
done
return 0
return 0
}
}


first_n_happy 8</syntaxhighlight>
first_n_happy 8</pre>
Output:<pre>1
7
10
13
19
23
28
31</pre>


=={{header|Ursala}}==
=={{header|Ursala}}==