Elm solution which does not use strings. Hopefully quite understandable.
sumDigitSquaressumnum=ifnum==0then-- exit condition, processed all digitssumelseletdigit=remnum10-- get right-most digitsquare=digit*digitnewNum=num//10-- remove right-most digitinsumDigitSquares(sum+square)newNumisHappyi=if0<=i&&i<=9then-- exit condition, single digit numberi==1||i==7elseletsum=sumDigitSquares0iinisHappysum
Two recursive functions. Exit conditions are getting a number between 0 and 9. Zero is impossible to actually get from other numbers, but there if someone input 0. The only happy numbers in that range are 1 and 7. Should work with negative numbers too.
Here is a runnable solution with UI to test a range of numbers. Try it at elm-lang.org/try.
importHtmlexposing(..)importHtml.Attributesexposing(..)importHtml.Eventsexposing(..)importTaskimportResultsumDigitSquaressumnum=ifnum==0thensumelseletdigit=remnum10square=digit*digitnewNum=num//10insumDigitSquares(sum+square)newNumisHappyi=if0<=i&&i<=9theni==1||i==7elseletsum=sumDigitSquares0iinisHappysumcalculateUpToi=List.range1i|>List.filterisHappy|>CalculateCompletedi-- UItypeMsg=NumberInputString|CalculateInt|CalculateCompletedInt(ListInt)typeCalculation=NotStarted|CalculatingInt|CalculatedInt(ListInt)typealiasModel={userInput:String,validatedNumber:ResultStringInt,calculation:Calculation}init={userInput="",validatedNumber=Err"",calculation=NotStarted}![]updatemsgmodel=casemsgofNumberInputs->{model|userInput=s,validatedNumber=String.toInts}![]Calculatei->{model|calculation=Calculatingi}![Task.performcalculateUpTo(Task.succeedi)]CalculateCompletedilist->{model|calculation=Calculatedilist}![]viewmodel=div[][div[][text"Check for happy numbers up to"],div[][input[type_"text",onInputNumberInput,valuemodel.userInput][]],div[][casemodel.validatedNumberofErrerr->button[type_"button",disabledTrue][text"Calculate"]Oki->button[type_"button",onClick(Calculatei)][text"Calculate"]],casemodel.calculationofNotStarted->text""Calculatingi->div[][hr[][],text("Calculating up to "++toStringi)]Calculatedilist->div[]([hr[][],div[][text("Happy numbers up to "++toStringi)]]++List.map(\num->div[][text(toStringnum)])list)]main=Html.program{init=init,view=view,update=update,subscriptions=\_->Sub.none}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Elm solution which does not use strings. Hopefully quite understandable.
Two recursive functions. Exit conditions are getting a number between 0 and 9. Zero is impossible to actually get from other numbers, but there if someone input 0. The only happy numbers in that range are 1 and 7. Should work with negative numbers too.
Here is a runnable solution with UI to test a range of numbers. Try it at elm-lang.org/try.