How to resolve the algorithm Happy numbers step by step in the UNIX Shell programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Happy numbers step by step in the UNIX Shell programming language
Table of Contents
Problem Statement
From Wikipedia, the free encyclopedia:
Find and print the first 8 happy numbers. Display an example of your output here on this page.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Happy numbers step by step in the UNIX Shell programming language
Source code in the unix programming language
function sum_of_square_digits {
typeset -i n=$1 sum=0 d
while (( n )); do
(( d=n%10, sum+=d*d, n=n/10 ))
done
printf '%d\n' "$sum"
}
function is_happy {
typeset -i n=$1
typeset -a seen=()
while (( n != 1 )); do
if [[ -n ${seen[$n]} ]]; then
return 1
fi
seen[$n]=1
(( n=$(sum_of_square_digits "$n") ))
done
return 0
}
function first_n_happy {
typeset -i count=$1 n
for (( n=1; count; n+=1 )); do
if is_happy "$n"; then
printf '%d\n' "$n"
(( count -= 1 ))
fi
done
return 0
}
first_n_happy 8
You may also check:How to resolve the algorithm Mind boggling card trick step by step in the Julia programming language
You may also check:How to resolve the algorithm File size step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm A+B step by step in the Pure programming language
You may also check:How to resolve the algorithm Abbreviations, simple step by step in the Yabasic programming language