Happy numbers: Difference between revisions

m
→‎{{header|Uiua}}: slightly nicer algorithm
(Applesoft BASIC)
m (→‎{{header|Uiua}}: slightly nicer algorithm)
 
(38 intermediate revisions by 19 users not shown)
Line 15:
Display an example of your output here on this page.
 
 
;Related tasks:
* [[Iterated digits squaring]]
 
;See also:
Line 24 ⟶ 27:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F happy(=n)
Set[Int] past
L n != 1
Line 33 ⟶ 36:
R 1B
 
print((0.<500).filter(x -> happy(x))[0.<8])</langsyntaxhighlight>
 
{{out}}
Line 52 ⟶ 55:
under 256, the cycle never goes above 163; this program could be trivially changed to print up to 39 happy numbers.
 
<langsyntaxhighlight lang="8080asm">flags: equ 2 ; 256-byte page in which to keep track of cycles
puts: equ 9 ; CP/M print string
bdos: equ 5 ; CP/M entry point
Line 128 ⟶ 131:
adi 10
ret ; 1s digit is left in A afterwards
string: db '000',13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 143 ⟶ 146:
 
=={{header|8th}}==
<langsyntaxhighlight lang="8th">
: until! "not while!" eval i;
 
Line 173 ⟶ 176:
;with
;with
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 180 ⟶ 183:
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO RETURN square.digit.sum n:
PUT 0 IN sum
WHILE n>0:
PUT n mod 10 IN digit
PUT sum + digit ** 2 IN sum
PUT floor (n/10) IN n
RETURN sum
 
HOW TO REPORT happy n:
PUT {} IN seen
WHILE n not.in seen:
INSERT n IN seen
PUT square.digit.sum n IN n
REPORT n=1
 
HOW TO RETURN next.happy n:
PUT n+1 IN n
WHILE NOT happy n: PUT n+1 IN n
RETURN n
 
PUT 0 IN n
FOR i IN {1..8}:
PUT next.happy n IN n
WRITE n/</syntaxhighlight>
{{out}}
<Pre>1
7
10
13
19
23
28
31</pre>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(include-book "arithmetic-3/top" :dir :system)
 
(defun sum-of-digit-squares (n)
Line 205 ⟶ 242:
 
(defun first-happy-nums (n)
(first-happy-nums-r n 1))</langsyntaxhighlight>
Output:
<pre>(1 7 10 13 19 23 28 31)</pre>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC SumOfSquares(BYTE x)
BYTE sum,d
 
Line 260 ⟶ 297:
x==+1
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Happy_numbers.png Screenshot from Atari 8-bit computer]
Line 275 ⟶ 312:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function sumOfSquares(n:uint)
{
var sum:uint = 0;
Line 316 ⟶ 353:
}
}
printHappy();</langsyntaxhighlight>
Sample output:
<pre>
Line 330 ⟶ 367:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
 
Line 370 ⟶ 407:
end if;
end loop;
end Test_Happy_Digits;</langsyntaxhighlight>
Sample output:
<pre>
Line 380 ⟶ 417:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">INT base10 = 10, num happy = 8;
 
PROC next = (INT in n)INT: (
Line 404 ⟶ 441:
print((i, new line))
FI
OD</langsyntaxhighlight>
Output:
<pre>
Line 418 ⟶ 455:
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algolm">begin
integer function mod(a,b);
integer a,b;
Line 455 ⟶ 492:
i := i + 1;
end;
end</langsyntaxhighlight>
{{out}}
<pre> 1
Line 467 ⟶ 504:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
begin % find some happy numbers: numbers whose digit-square sums become 1 %
% when repeatedly applied %
% returns true if n is happy, false otherwise; n must be >= 0 %
% returns true if n is happy, false otherwise %
logical procedure isHappy( integer value n ) ;
logical procedure isHappy ( integer value n ) ;
if n < 2 then true
else begin
% seen is used to hold the values of the cycle of the %
% digit square sums, as noted in the Batch File %
% version, we do not need a large array. The digit %
% square sum of 9 999 999 999 is 810... %
integer array seen( 0 :: 32 );
integer number, trys;
number := n;
trys := -1;
while begin
logical terminated;
integer tPos;
terminated := false;
tPos := 0;
while not terminated and tPos <= trys do begin
terminated := seen( tPos ) = number;
tPos := tPos + 1
end while_not_terminated_and_tPos_lt_trys ;
number > 1 and not terminated
end do begin
integer sum;
trys := trys + 1;
seen( trys ) := number;
sum := 0;
while number > 0 do begin
integer digit;
digit := number rem 10;
number := number div 10;
sum := sum + ( digit * digit )
end while_number_gt_0 ;
number := sum
end while_number_gt_1_and_not_terminated ;
number = 1
end isHappy ;
% print the first 8 happy numbers %
begin
% in base ten, numbers either reach 1 or loop around a sequence %
integer happyCount, n;
% containing 4 (see the Wikipedia article) %
happyCount := 0;
ninteger v, dSum, := 1d;
write(v "first 8 happy numbers:= "abs )n;
whileif happyCountv <> 81 dothen begin
while begin
dSum := 0;
while v not = 0 do begin
d := v rem 10;
v := v div 10;
dSum := dSum + ( d * d )
end while_v_ne_0 ;
v := dSum;
v not = 1 and v not = 4
end do begin end
end if_v_ne_0 ;
v = 1
end isHappy ;
begin % find the first 8 happy numbers %
integer n, hCount;
hCount := 0;
n := 1;
while hCount < 8 do begin
if isHappy( n ) then begin
writeon( i_w := 1, s_w := 0, " ", n );
happyCounthCount := happyCounthCount + 1
end if_isHappy_nif_isHappy__n ;
n := n + 1
end while_happyCount_lt_8while_hCount_lt_10
end
end.</lang>
</syntaxhighlight>
{{out}}
<pre>
first 8 happy numbers: 1 7 10 13 19 23 28 31
</pre>
 
Line 529 ⟶ 550:
 
===Tradfn===
<langsyntaxhighlight APLlang="apl"> ∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
[1] ⍝0: Happy number
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
Line 548 ⟶ 569:
[17]
[18] ⎕←~∘0¨∆first↑bin/iroof ⍝ Show ∆first numbers, but not 0
∇</langsyntaxhighlight>
<pre>
HappyNumbers 100 8
Line 555 ⟶ 576:
 
===Dfn===
<syntaxhighlight lang="apl">
<lang APL>
HappyNumbers←{ ⍝ return the first ⍵ Happy Numbers
⍺←⍬ ⍝ initial list
Line 570 ⟶ 591:
HappyNumbers 8
1 7 10 13 19 23 28 31
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
 
===Iteration===
<langsyntaxhighlight AppleScriptlang="applescript">on run
set howManyHappyNumbers to 8
set happyNumberList to {}
Line 606 ⟶ 627:
end repeat
return (numberToCheck = 1)
end isHappy</langsyntaxhighlight>
<pre>
Result: (*1, 7, 10, 13, 19, 23, 28, 31*)
Line 614 ⟶ 635:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">---------------------- HAPPY NUMBERS -----------------------
 
-- isHappy :: Int -> Bool
Line 740 ⟶ 761:
end tell
return v
end |until|</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{1, 7, 10, 13, 19, 23, 28, 31}</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<lang gwbasic> 0 C = 8: DIM S(16):B = 10: PRINT "THE FIRST "C" HAPPY NUMBERS": FOR R = C TO 0 STEP 0:N = H: GOSUB 1: PRINT MID$ (" " + STR$ (H),1 + (R = C),255 * I);:R = R - I:H = H + 1: NEXT R: END
1 S = 0: GOSUB 3:I = N = 1: IF NOT Q THEN RETURN
2 FOR Q = 1 TO 0 STEP 0:S(S) = N:S = S + 1: GOSUB 6:N = T: GOSUB 3: NEXT Q:I = N = 1: RETURN
3 Q = N > 1: IF NOT Q OR NOT S THEN RETURN
4 Q = 0: FOR I = 0 TO S - 1: IF N = S(I) THEN RETURN
5 NEXT I:Q = 1: RETURN
6 T = 0: FOR I = N TO 0 STEP 0:M = INT (I / B):T = INT (T + (I - M * B) ^ 2):I = M: NEXT I: RETURN</lang>
{{out}}
<pre>
THE FIRST 8 HAPPY NUMBERS
1 7 10 13 19 23 28 31
</pre>
=={{header|Arturo}}==
 
{{trans|Nim}}
 
<langsyntaxhighlight lang="rebol">ord0: to :integer `0`
happy?: function [x][
n: x
Line 781 ⟶ 789:
loop 0..31 'x [
if happy? x -> print x
]</langsyntaxhighlight>
 
{{out}}
Line 795 ⟶ 803:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop {
If isHappy(A_Index) {
out .= (out="" ? "" : ",") . A_Index
Line 815 ⟶ 823:
Return false
Else Return isHappy(sum, list)
}</langsyntaxhighlight>
<pre>
The first 8 happy numbers are: 1,7,10,13,19,23,28,31
</pre>
===Alternative version===
<langsyntaxhighlight AutoHotkeylang="autohotkey">while h < 8
if (Happy(A_Index)) {
Out .= A_Index A_Space
Line 837 ⟶ 845:
n := t, t := 0
}
}</langsyntaxhighlight>
<pre>1 7 10 13 19 23 28 31</pre>
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">
$c = 0
$k = 0
Line 864 ⟶ 872:
EndIf
WEnd
</syntaxhighlight>
</lang>
 
<pre>
Line 880 ⟶ 888:
 
===Alternative version===
<langsyntaxhighlight lang="autoit">
$c = 0
$k = 0
Line 905 ⟶ 913:
$a.Clear
WEnd
</syntaxhighlight>
</lang>
<pre>
Saves all numbers in a list, duplicate entry indicates a loop.
Line 920 ⟶ 928:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function is_happy(n)
{
if ( n in happy ) return 1;
Line 960 ⟶ 968:
}
}
}</langsyntaxhighlight>
Result:
<pre>1
Line 975 ⟶ 983:
Alternately, for legibility one might write:
 
<langsyntaxhighlight lang="awk">BEGIN {
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
Line 1,002 ⟶ 1,010:
}
return tot
}</langsyntaxhighlight>
 
=={{header|BASIC256BASIC}}==
==={{header|Applesoft BASIC}}===
<lang freebasic>n = 1 : cnt = 0
<syntaxhighlight lang="gwbasic"> 0 C = 8: DIM S(16):B = 10: PRINT "THE FIRST "C" HAPPY NUMBERS": FOR R = C TO 0 STEP 0:N = H: GOSUB 1: PRINT MID$ (" " + STR$ (H),1 + (R = C),255 * I);:R = R - I:H = H + 1: NEXT R: END
1 S = 0: GOSUB 3:I = N = 1: IF NOT Q THEN RETURN
2 FOR Q = 1 TO 0 STEP 0:S(S) = N:S = S + 1: GOSUB 6:N = T: GOSUB 3: NEXT Q:I = N = 1: RETURN
3 Q = N > 1: IF NOT Q OR NOT S THEN RETURN
4 Q = 0: FOR I = 0 TO S - 1: IF N = S(I) THEN RETURN
5 NEXT I:Q = 1: RETURN
6 T = 0: FOR I = N TO 0 STEP 0:M = INT (I / B):T = INT (T + (I - M * B) ^ 2):I = M: NEXT I: RETURN</syntaxhighlight>
{{out}}
<pre>
THE FIRST 8 HAPPY NUMBERS
1 7 10 13 19 23 28 31
</pre>
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">n = 1 : cnt = 0
print "The first 8 isHappy numbers are:"
print
Line 1,029 ⟶ 1,051:
num = isHappy
end while
end function</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> number% = 0
total% = 0
REPEAT
number% += 1
IF FNhappy(number%) THEN
PRINT number% " is a happy number"
total% += 1
ENDIF
UNTIL total% = 8
END
DEF FNhappy(num%)
LOCAL digit&()
DIM digit&(10)
REPEAT
digit&() = 0
$$^digit&(0) = STR$(num%)
digit&() AND= 15
num% = MOD(digit&())^2 + 0.5
UNTIL num% = 1 OR num% = 4
= (num% = 1)</syntaxhighlight>
Output:
<pre> 1 is a happy number
7 is a happy number
10 is a happy number
13 is a happy number
19 is a happy number
23 is a happy number
28 is a happy number
31 is a happy number</pre>
 
==={{header|Commodore BASIC}}===
The array sizes here are tuned to the minimum values required to find the first 8 happy numbers in numerical order. The <tt>H</tt> and <tt>U</tt> arrays are used for memoization, so the subscripts <tt>H(</tt><i>n</i><tt>)</tt> and <tt>U(</tt><i>n</i><tt>)</tt> must exist for the highest <i>n</i> encountered. The array <tt>N</tt> must have room to hold the longest chain examined in the course of determining whether a single number is happy, which thanks to the memoization is only ten elements long.
 
<syntaxhighlight lang="gwbasic">
100 C=8:DIM H(145),U(145),N(9)
110 PRINT CHR$(147):PRINT "THE FIRST"C"HAPPY NUMBERS:":PRINT
120 H(1)=1:N=1
130 FOR C=C TO 0 STEP 0
140 : GOSUB 200
150 : IF H THEN PRINT N,:C=C-1
160 : N=N+1
170 NEXT C
180 PRINT
190 END
200 K=0:N(K)=N
210 IF H(N(K)) THEN H=1:FOR J=0 TO K:U(N(J))=0:H(N(J))=1:NEXT J:RETURN
220 IF U(N(K)) THEN H=0:RETURN
230 U(N(K))=1
240 N$=MID$(STR$(N(K)),2)
250 L=LEN(N$)
260 K=K+1:N(K)=0
270 FOR I=1 TO L
280 : D = VAL(MID$(N$,I,1))
290 : N(K) = N(K) + D * D
300 NEXT I
310 GOTO 210</syntaxhighlight>
 
{{Out}}
<pre>
THE FIRST 8 HAPPY NUMBERS:
 
1 7 10 13
19 23 28 31
 
 
READY.
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isHappy(n As Integer) As Boolean
If n < 0 Then Return False
' Declare a dynamic array to store previous sums.
' If a previous sum is duplicated before a sum of 1 is reached
' then the number can't be "happy" as the cycle will just repeat
Dim prevSums() As Integer
Dim As Integer digit, ub, sum = 0
Do
While n > 0
digit = n Mod 10
sum += digit * digit
n \= 10
Wend
If sum = 1 Then Return True
ub = UBound(prevSums)
If ub > -1 Then
For i As Integer = 0 To ub
If sum = prevSums(i) Then Return False
Next
End If
ub += 1
Redim Preserve prevSums(0 To ub)
prevSums(ub) = sum
n = sum
sum = 0
Loop
End Function
Dim As Integer n = 1, count = 0
 
Print "The first 8 happy numbers are : "
Print
While count < 8
If isHappy(n) Then
count += 1
Print count;" =>"; n
End If
n += 1
Wend
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
1 => 1
2 => 7
3 => 10
4 => 13
5 => 19
6 => 23
7 => 28
8 => 31
</pre>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb"> ct = 0
n = 0
DO
n = n + 1
IF HappyN(n, sqrInt$) = 1 THEN
ct = ct + 1
PRINT ct, n
END IF
LOOP UNTIL ct = 8
END
 
FUNCTION HappyN(n, sqrInts$)
n$ = Str$(n)
sqrInts = 0
FOR i = 1 TO Len(n$)
sqrInts = sqrInts + Val(Mid$(n$, i, 1)) ^ 2
NEXT i
IF sqrInts = 1 THEN
HappyN = 1
EXIT FUNCTION
END IF
IF Instr(sqrInts$, ":";Str$(sqrInts);":") > 0 THEN
HappyN = 0
EXIT FUNCTION
END IF
sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
HappyN = HappyN(sqrInts, sqrInts$)
END FUNCTION</syntaxhighlight>
Output:-
<pre>1 1
2 7
3 10
4 13
5 19
6 23
7 28
8 31
</pre>
 
==={{header|Locomotive Basic}}===
 
<syntaxhighlight lang="locobasic">10 mode 1:defint a-z
20 for i=1 to 100
30 i2=i
40 for l=1 to 20
50 a$=str$(i2)
60 i2=0
70 for j=1 to len(a$)
80 d=val(mid$(a$,j,1))
90 i2=i2+d*d
100 next j
110 if i2=1 then print i;"is a happy number":n=n+1:goto 150
120 if i2=4 then 150 ' cycle found
130 next l
140 ' check if we have reached 8 numbers yet
150 if n=8 then end
160 next i</syntaxhighlight>
 
[[File:Happy Numbers, Locomotive BASIC.png]]
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">#ToFind=8
#MaxTests=100
#True = 1: #False = 0
Declare is_happy(n)
 
If OpenConsole()
Define i=1,Happy
Repeat
If is_happy(i)
Happy+1
PrintN("#"+Str(Happy)+RSet(Str(i),3))
EndIf
i+1
Until Happy>=#ToFind
;
Print(#CRLF$+#CRLF$+"Press ENTER to exit"): Input()
CloseConsole()
EndIf
 
Procedure is_happy(n)
Protected i,j=n,dig,sum
Repeat
sum=0
While j
dig=j%10
j/10
sum+dig*dig
Wend
If sum=1: ProcedureReturn #True: EndIf
j=sum
i+1
Until i>#MaxTests
ProcedureReturn #False
EndProcedure</syntaxhighlight>
Sample output:
<pre>#1 1
#2 7
#3 10
#4 13
#5 19
#6 23
#7 28
#8 31</pre>
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 1 to 100
if happy(i) = 1 then
cnt = cnt + 1
PRINT cnt;". ";i;" is a happy number "
if cnt = 8 then end
end if
next i
FUNCTION happy(num)
while count < 50 and happy <> 1
num$ = str$(num)
count = count + 1
happy = 0
for i = 1 to len(num$)
happy = happy + val(mid$(num$,i,1)) ^ 2
next i
num = happy
wend
end function</syntaxhighlight>
<pre>1. 1 is a happy number
2. 7 is a happy number
3. 10 is a happy number
4. 13 is a happy number
5. 19 is a happy number
6. 23 is a happy number
7. 28 is a happy number
8. 31 is a happy number
</pre>
 
 
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">
' ************************
' MAIN
' ************************
 
PROC _PRINT_HAPPY(20)
END
 
' ************************
' END MAIN
' ************************
 
' ************************
' SUBS & FUNCTIONS
' ************************
 
' --------------------
_is_happy PARAM(1)
' --------------------
LOCAL (5)
f@ = 100
c@ = a@
b@ = 0
 
DO WHILE b@ < f@
e@ = 0
 
DO WHILE c@
d@ = c@ % 10
c@ = c@ / 10
e@ = e@ + (d@ * d@)
LOOP
 
UNTIL e@ = 1
c@ = e@
b@ = b@ + 1
LOOP
 
RETURN(b@ < f@)
 
' --------------------
_PRINT_HAPPY PARAM(1)
' --------------------
LOCAL (2)
b@ = 1
c@ = 0
 
DO
 
IF FUNC (_is_happy(b@)) THEN
c@ = c@ + 1
PRINT b@
ENDIF
 
b@ = b@ + 1
UNTIL c@ + 1 > a@
LOOP
 
RETURN
 
' ************************
' END SUBS & FUNCTIONS
' ************************
</syntaxhighlight>
 
==={{header|VBA}}===
 
<syntaxhighlight lang="vb">
Option Explicit
 
Sub Test_Happy()
Dim i&, Cpt&
 
For i = 1 To 100
If Is_Happy_Number(i) Then
Debug.Print "Is Happy : " & i
Cpt = Cpt + 1
If Cpt = 8 Then Exit For
End If
Next
End Sub
 
Public Function Is_Happy_Number(ByVal N As Long) As Boolean
Dim i&, Number$, Cpt&
Is_Happy_Number = False 'default value
Do
Cpt = Cpt + 1 'Count Loops
Number = CStr(N) 'conversion Long To String to be able to use Len() function
N = 0
For i = 1 To Len(Number)
N = N + CInt(Mid(Number, i, 1)) ^ 2
Next i
'If Not N = 1 after 50 Loop ==> Number Is Not Happy
If Cpt = 50 Then Exit Function
Loop Until N = 1
Is_Happy_Number = True
End Function
</syntaxhighlight>
{{Out}}
<pre>Is Happy : 1
Is Happy : 7
Is Happy : 10
Is Happy : 13
Is Happy : 19
Is Happy : 23
Is Happy : 28
Is Happy : 31</pre>
 
 
==={{header|VBScript}}===
<syntaxhighlight lang="vb">
count = 0
firsteigth=""
For i = 1 To 100
If IsHappy(CInt(i)) Then
firsteight = firsteight & i & ","
count = count + 1
End If
If count = 8 Then
Exit For
End If
Next
WScript.Echo firsteight
 
Function IsHappy(n)
IsHappy = False
m = 0
Do Until m = 60
sum = 0
For j = 1 To Len(n)
sum = sum + (Mid(n,j,1))^2
Next
If sum = 1 Then
IsHappy = True
Exit Do
Else
n = sum
m = m + 1
End If
Loop
End Function
</syntaxhighlight>
 
{{Out}}
<pre>1,7,10,13,19,23,28,31,</pre>
 
==={{header|Visual Basic .NET}}===
This version uses Linq to carry out the calculations.
<syntaxhighlight lang="vbnet">Module HappyNumbers
Sub Main()
Dim n As Integer = 1
Dim found As Integer = 0
 
Do Until found = 8
If IsHappy(n) Then
found += 1
Console.WriteLine("{0}: {1}", found, n)
End If
n += 1
Loop
 
Console.ReadLine()
End Sub
 
Private Function IsHappy(ByVal n As Integer)
Dim cache As New List(Of Long)()
 
Do Until n = 1
cache.Add(n)
n = Aggregate c In n.ToString() _
Into Total = Sum(Int32.Parse(c) ^ 2)
If cache.Contains(n) Then Return False
Loop
 
Return True
End Function
End Module</syntaxhighlight>
The output is:
<pre>1: 1
2: 7
3: 10
4: 13
5: 19
6: 23
7: 28
8: 31</pre>
====Cacheless version====
{{trans|C#}}
Curiously, this runs in about two thirds of the time of the cacheless C# version on Tio.run.
<syntaxhighlight lang="vbnet">Module Module1
 
Dim sq As Integer() = {1, 4, 9, 16, 25, 36, 49, 64, 81}
 
Function isOne(x As Integer) As Boolean
While True
If x = 89 Then Return False
Dim t As Integer, s As Integer = 0
Do
t = (x Mod 10) - 1 : If t >= 0 Then s += sq(t)
x \= 10
Loop While x > 0
If s = 1 Then Return True
x = s
End While
Return False
End Function
 
Sub Main(ByVal args As String())
Const Max As Integer = 10_000_000
Dim st As DateTime = DateTime.Now
Console.Write("---Happy Numbers---" & vbLf & "The first 8:")
Dim i As Integer = 1, c As Integer = 0
While c < 8
If isOne(i) Then Console.Write("{0} {1}", If(c = 0, "", ","), i, c) : c += 1
i += 1
End While
Dim m As Integer = 10
While m <= Max
Console.Write(vbLf & "The {0:n0}th: ", m)
While c < m
If isOne(i) Then c += 1
i += 1
End While
Console.Write("{0:n0}", i - 1)
m = m * 10
End While
Console.WriteLine(vbLf & "Computation time {0} seconds.", (DateTime.Now - st).TotalSeconds)
End Sub
End Module</syntaxhighlight>
{{out}}
<pre>---Happy Numbers---
The first 8: 1, 7, 10, 13, 19, 23, 28, 31
The 10th: 44
The 100th: 694
The 1,000th: 6,899
The 10,000th: 67,169
The 100,000th: 692,961
The 1,000,000th: 7,105,849
The 10,000,000th: 71,313,350
Computation time 19.235551 seconds.</pre>
 
==={{header|ZX Spectrum Basic}}===
{{trans|Run_BASIC}}
<syntaxhighlight lang="zxbasic">10 FOR i=1 TO 100
20 GO SUB 1000
30 IF isHappy=1 THEN PRINT i;" is a happy number"
40 NEXT i
50 STOP
1000 REM Is Happy?
1010 LET isHappy=0: LET count=0: LET num=i
1020 IF count=50 OR isHappy=1 THEN RETURN
1030 LET n$=STR$ (num)
1040 LET count=count+1
1050 LET isHappy=0
1060 FOR j=1 TO LEN n$
1070 LET isHappy=isHappy+VAL n$(j)^2
1080 NEXT j
1090 LET num=isHappy
1100 GO TO 1020</syntaxhighlight>
=={{header|Batch File}}==
happy.bat
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
::Define a list with 10 terms as a convenience for defining a loop
Line 1,113 ⟶ 1,661:
)
set /a n=sum
)</langsyntaxhighlight>
Sample usage and output
<pre>
Line 1,170 ⟶ 1,718:
ERROR: Maximum integer value reached
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> number% = 0
total% = 0
REPEAT
number% += 1
IF FNhappy(number%) THEN
PRINT number% " is a happy number"
total% += 1
ENDIF
UNTIL total% = 8
END
DEF FNhappy(num%)
LOCAL digit&()
DIM digit&(10)
REPEAT
digit&() = 0
$$^digit&(0) = STR$(num%)
digit&() AND= 15
num% = MOD(digit&())^2 + 0.5
UNTIL num% = 1 OR num% = 4
= (num% = 1)</lang>
Output:
<pre> 1 is a happy number
7 is a happy number
10 is a happy number
13 is a happy number
19 is a happy number
23 is a happy number
28 is a happy number
31 is a happy number</pre>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let sumdigitsq(n) =
Line 1,229 ⟶ 1,744:
$)
wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
 
=={{header|Bori}}==
<langsyntaxhighlight lang="bori">bool isHappy (int n)
{
ints cache;
Line 1,269 ⟶ 1,784:
}
puts("First 8 happy numbers : " + str.newline + happynums);
}</langsyntaxhighlight>
Output:
<pre>First 8 happy numbers :
Line 1,275 ⟶ 1,790:
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">SumSqDgt ← +´2⋆˜ •Fmt-'0'˙
Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢
8↑Happy¨⊸/↕50</langsyntaxhighlight>
{{out}}
<pre>⟨ 1 7 10 13 19 23 28 31 ⟩</pre>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">include :set
 
happiness = set.new 1
Line 1,310 ⟶ 1,825:
p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"</langsyntaxhighlight>
Output:
<pre>First eight happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]
Line 1,318 ⟶ 1,833:
=={{header|C}}==
Recursively look up if digit square sum is happy.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define CACHE 256
Line 1,350 ⟶ 1,865:
 
return 0;
}</langsyntaxhighlight>
output<pre>1 7 10 13 19 23 28 31
The 1000000th happy number: 7105849</pre>
Without caching, using cycle detection:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int dsum(int n)
Line 1,384 ⟶ 1,899:
 
return 0;
}</langsyntaxhighlight> Output is same as above, but much slower.
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,435 ⟶ 1,950:
}
}
}</langsyntaxhighlight>
<pre>
First 8 happy numbers : 1,7,10,13,19,23,28,31
Line 1,442 ⟶ 1,957:
===Alternate (cacheless)===
Instead of caching and checking for being stuck in a loop, one can terminate on the "unhappy" endpoint of 89. One might be temped to try caching the so-far-found happy and unhappy numbers and checking the cache to speed things up. However, I have found that the cache implementation overhead reduces performance compared to this cacheless version.<br/>
Reaching 10 million, the <34 second computation time was from Tio.run. It takes under 5 seconds on a somewhat modern CPU. If you edit it to max out at 100 million, it takes about 50 seconds (on the somewhat modern CPU).<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
class Program
Line 1,475 ⟶ 1,990:
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}</langsyntaxhighlight>
{{out}}
<pre>---Happy Numbers---
Line 1,490 ⟶ 2,005:
=={{header|C++}}==
{{trans|Python}}
<langsyntaxhighlight lang="cpp">#include <map>
#include <set>
 
Line 1,525 ⟶ 2,040:
std::cout << i << std::endl;
return 0;
}</langsyntaxhighlight>
Output:
<pre>1
Line 1,539 ⟶ 2,054:
49</pre>
Alternative version without caching:
<langsyntaxhighlight lang="cpp">unsigned int happy_iteration(unsigned int n)
{
unsigned int result = 0;
Line 1,579 ⟶ 2,094:
}
std::cout << std::endl;
}</langsyntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 1,585 ⟶ 2,100:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn happy? [n]
(loop [n n, seen #{}]
(cond
Line 1,599 ⟶ 2,114:
(def happy-numbers (filter happy? (iterate inc 1)))
 
(println (take 8 happy-numbers))</langsyntaxhighlight>
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
===Alternate Version (with caching)===
<langsyntaxhighlight lang="clojure">(require '[clojure.set :refer [union]])
 
(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})})
Line 1,636 ⟶ 2,151:
(filter #(= :happy (happy-algo %)))))
 
(println (take 8 happy-numbers))</langsyntaxhighlight>
Same output.
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">sum_dig_sq = proc (n: int) returns (int)
sum_sq: int := 0
while n > 0 do
Line 1,675 ⟶ 2,190:
stream$putl(po, int$unparse(i))
end
end start_up </langsyntaxhighlight>
{{out}}
<pre>1
Line 1,685 ⟶ 2,200:
28
31</pre>
 
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. HAPPY.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 CANDIDATE PIC 9(4).
03 SQSUM-IN PIC 9(4).
03 FILLER REDEFINES SQSUM-IN.
05 DIGITS PIC 9 OCCURS 4 TIMES.
03 SQUARE PIC 9(4).
03 SUM-OF-SQUARES PIC 9(4).
03 N PIC 9.
03 TORTOISE PIC 9(4).
03 HARE PIC 9(4).
88 HAPPY VALUE 1.
03 SEEN PIC 9 VALUE ZERO.
03 OUT-FMT PIC ZZZ9.
 
PROCEDURE DIVISION.
BEGIN.
PERFORM DISPLAY-IF-HAPPY VARYING CANDIDATE FROM 1 BY 1
UNTIL SEEN IS EQUAL TO 8.
STOP RUN.
 
DISPLAY-IF-HAPPY.
PERFORM CHECK-HAPPY.
IF HAPPY,
MOVE CANDIDATE TO OUT-FMT,
DISPLAY OUT-FMT,
ADD 1 TO SEEN.
CHECK-HAPPY.
MOVE CANDIDATE TO TORTOISE, SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO HARE.
PERFORM CHECK-HAPPY-STEP UNTIL TORTOISE IS EQUAL TO HARE.
CHECK-HAPPY-STEP.
MOVE TORTOISE TO SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO TORTOISE.
MOVE HARE TO SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO HARE.
CALC-SUM-OF-SQUARES.
MOVE ZERO TO SUM-OF-SQUARES.
PERFORM ADD-DIGIT-SQUARE VARYING N FROM 1 BY 1
UNTIL N IS GREATER THAN 4.
ADD-DIGIT-SQUARE.
MULTIPLY DIGITS(N) BY DIGITS(N) GIVING SQUARE.
ADD SQUARE TO SUM-OF-SQUARES.</syntaxhighlight>
{{out}}
<pre> 1
7
10
13
19
23
28
31</pre>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">happy = (n) ->
seen = {}
while true
Line 1,708 ⟶ 2,290:
console.log i
cnt += 1
i += 1</langsyntaxhighlight>
output
<pre>
Line 1,723 ⟶ 2,305:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun sqr (n)
(* n n))
 
Line 1,744 ⟶ 2,326:
(print (happys))
</syntaxhighlight>
</lang>
 
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub sumDigitSquare(n: uint8): (s: uint8) is
Line 1,786 ⟶ 2,368:
end if;
n := n + 1;
end loop;</langsyntaxhighlight>
 
{{out}}
Line 1,801 ⟶ 2,383:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def happy?(n)
past = [] of Int32 | Int64
until n == 1
Line 1,814 ⟶ 2,396:
until count == 8; (puts i; count += 1) if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</langsyntaxhighlight>
{{out}}
<pre>
Line 1,840 ⟶ 2,422:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">bool isHappy(int n) pure nothrow {
int[int] past;
 
Line 1,862 ⟶ 2,444:
 
int.max.iota.filter!isHappy.take(8).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
===Alternative Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv, std.string;
 
bool isHappy(int n) pure nothrow {
Line 1,884 ⟶ 2,466:
void main() {
int.max.iota.filter!isHappy.take(8).writeln;
}</langsyntaxhighlight>
Same output.
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">main() {
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
Line 1,922 ⟶ 2,504:
i++;
}
}</langsyntaxhighlight>
 
=={{header|dc}}==
<langsyntaxhighlight lang="dc">[lcI~rscd*+lc0<H]sH
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx</langsyntaxhighlight>
Output:
<pre>1
Line 1,940 ⟶ 2,522:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ happy_1 = 1
$ found = 0
$ i = 1
Line 1,989 ⟶ 2,571:
$ goto loop1
$ done:
$ show symbol found*</langsyntaxhighlight>
{{out}}
<pre> FOUND = 8 Hex = 00000008 Octal = 00000000010
Line 2,004 ⟶ 2,586:
{{libheader| Boost.Int}}
Adaptation of [[#Pascal]]. The lib '''Boost.Int''' can be found here [https://github.com/MaiconSoft/DelphiBoostLib]
<syntaxhighlight lang="delphi">
<lang Delphi>
program Happy_numbers;
 
Line 2,068 ⟶ 2,650:
writeln;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec dsumsq(byte n) byte:
byte r, d;
r := 0;
Line 2,105 ⟶ 2,687:
n := n + 1
od
corp</langsyntaxhighlight>
{{out}}
<pre> 1
Line 2,117 ⟶ 2,699:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">function IsHappy(n : Integer) : Boolean;
var
cache : array of Integer;
Line 2,146 ⟶ 2,728:
Dec(n);
end;
end;</langsyntaxhighlight>
Output:
<pre>1
Line 2,159 ⟶ 2,741:
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func happy(n) {
var m = []
while n > 1 {
Line 2,185 ⟶ 2,767:
n += 1
}
print()</langsyntaxhighlight>
 
{{out}}
Line 2,192 ⟶ 2,774:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">next-num:
0
while over:
Line 2,228 ⟶ 2,810:
++
drop
drop</langsyntaxhighlight>
{{output}}
<pre>A happy number: 1
Line 2,241 ⟶ 2,823:
=={{header|E}}==
{{output?|E}}
<langsyntaxhighlight lang="e">def isHappyNumber(var x :int) {
var seen := [].asSet()
while (!seen.contains(x)) {
Line 2,260 ⟶ 2,842:
println(x)
if ((count += 1) >= 8) { break }
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func dsum n .
while n > 0
d = n mod 10
s += d * d
n = n div 10
.
return s
.
func happy n .
while n > 999
n = dsum n
.
len seen[] 999
repeat
n = dsum n
until seen[n] = 1
seen[n] = 1
.
return if n = 1
.
while cnt < 8
n += 1
if happy n = 1
cnt += 1
write n & " "
.
.
</syntaxhighlight>
{{out}}
<pre>
1 7 10 13 19 23 28 31
</pre>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 2,335 ⟶ 2,952:
end
 
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'collections;
import system'routines;
Line 2,351 ⟶ 2,968:
while (num != 1)
{
if (cache.indexOfElement:(num) != -1)
{
^ false
Line 2,358 ⟶ 2,975:
while (num != 0)
{
int digit := num.mod:(10);
sum += (digit*digit);
num /= 10
Line 2,383 ⟶ 3,000:
};
console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,390 ⟶ 3,007:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Happy do
def task(num) do
Process.put({:happy, 1}, true)
Line 2,416 ⟶ 3,033:
end
 
IO.inspect Happy.task(8)</langsyntaxhighlight>
 
{{out}}
Line 2,424 ⟶ 3,041:
 
=={{header|Erlang}}==
<langsyntaxhighlight Erlanglang="erlang">-module(tasks).
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
Line 2,456 ⟶ 3,073:
main() ->
main(0, []).
</syntaxhighlight>
</lang>
Command: <langsyntaxhighlight Bashlang="bash">erl -run tasks main -run init stop -noshell</langsyntaxhighlight>
Output: <langsyntaxhighlight Bashlang="bash">8 Happy Numbers: [1,7,10,13,19,23,28,31]</langsyntaxhighlight>
 
In a more functional style (assumes integer_to_list/1 will convert to the ASCII value of a number, which then has to be converted to the integer value by subtracting 48):
<langsyntaxhighlight Erlanglang="erlang">-module(tasks).
 
-export([main/0]).
Line 2,478 ⟶ 3,095:
N_As_Digits = [Y - 48 || Y <- integer_to_list(N)],
is_happy(lists:foldl(fun(X, Sum) -> (X * X) + Sum end, 0, N_As_Digits));
is_happy(_) -> false.</langsyntaxhighlight>
Output:
<pre>[1,7,10,13,19,23,28,31]</pre>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function is_happy(integer n)
sequence seen
integer k
Line 2,511 ⟶ 3,128:
end if
n += 1
end while</langsyntaxhighlight>
Output:
<pre>1
Line 2,525 ⟶ 3,142:
=={{header|F_Sharp|F#}}==
This requires the F# power pack to be referenced and the 2010 beta of F#
<langsyntaxhighlight lang="fsharp">open System.Collections.Generic
open Microsoft.FSharp.Collections
 
Line 2,554 ⟶ 3,171:
|> Seq.truncate 8 // Stop when we've found 8
|> Seq.iter (Printf.printf "%d\n") // Print results
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,568 ⟶ 3,185:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators kernel make math sequences ;
 
: squares ( n -- s )
Line 2,588 ⟶ 3,205:
dup happy? [ dup , [ 1 - ] dip ] when 1 +
] while 2drop
] { } make ;</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="factor">8 happy-numbers ! { 1 7 10 13 19 23 28 31 }</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[$10/$10*@\-$*\]m: {modulo squared and division}
[$m;![$9>][m;!@@+\]#$*+]s: {sum of squares}
[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates}
Line 2,607 ⟶ 3,224:
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%</langsyntaxhighlight>
 
{{out}}
Line 2,613 ⟶ 3,230:
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class Main
{
static Bool isHappy (Int n)
Line 2,648 ⟶ 3,265:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,662 ⟶ 3,279:
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="focal">01.10 S J=0;S N=1;T %2
01.20 D 3;I (K-2)1.5
01.30 S N=N+1
Line 2,680 ⟶ 3,297:
03.30 S S(K)=0
03.40 D 2;S K=R
03.50 I (S(K))3.3</langsyntaxhighlight>
 
{{out}}
Line 2,694 ⟶ 3,311:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: next ( n -- n )
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
 
Line 2,713 ⟶ 3,330:
loop drop ;
 
8 happy-numbers \ 1 7 10 13 19 23 28 31</langsyntaxhighlight>
 
===Lookup Table===
Every sequence either ends in 1, or contains a 4 as part of a cycle. Extending the table through 9 is a (modest) optimization/memoization. This executes '500000 happy-numbers' about 5 times faster than the above solution.
<langsyntaxhighlight lang="forth">CREATE HAPPINESS 0 C, 1 C, 0 C, 0 C, 0 C, 0 C, 0 C, 1 C, 0 C, 0 C,
: next ( n -- n')
0 swap BEGIN dup WHILE 10 /mod >r dup * + r> REPEAT drop ;
Line 2,726 ⟶ 3,343:
BEGIN 1+ dup happy? UNTIL dup . r> 1- >r
REPEAT r> drop drop ;
8 happy-numbers</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Produces the 1 millionth happy number with:
<langsyntaxhighlight lang="forth">: happy-number ( n -- n') \ produce the nth happy number
>r 0 BEGIN r@ WHILE
BEGIN 1+ dup happy? UNTIL r> 1- >r
REPEAT r> drop ;
1000000 happy-number . \ 7105849</langsyntaxhighlight>
in about 9 seconds.
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program happy
 
implicit none
Line 2,804 ⟶ 3,421:
end function is_happy
 
end program happy</langsyntaxhighlight>
Output:
<pre>1
Line 2,814 ⟶ 3,431:
28
31</pre>
 
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
 
Function isHappy(n As Integer) As Boolean
If n < 0 Then Return False
' Declare a dynamic array to store previous sums.
' If a previous sum is duplicated before a sum of 1 is reached
' then the number can't be "happy" as the cycle will just repeat
Dim prevSums() As Integer
Dim As Integer digit, ub, sum = 0
Do
While n > 0
digit = n Mod 10
sum += digit * digit
n \= 10
Wend
If sum = 1 Then Return True
ub = UBound(prevSums)
If ub > -1 Then
For i As Integer = 0 To ub
If sum = prevSums(i) Then Return False
Next
End If
ub += 1
Redim Preserve prevSums(0 To ub)
prevSums(ub) = sum
n = sum
sum = 0
Loop
End Function
Dim As Integer n = 1, count = 0
 
Print "The first 8 happy numbers are : "
Print
While count < 8
If isHappy(n) Then
count += 1
Print count;" =>"; n
End If
n += 1
Wend
Print
Print "Press any key to quit"
Sleep</lang>
 
{{out}}
<pre>
1 => 1
2 => 7
3 => 10
4 => 13
5 => 19
6 => 23
7 => 28
8 => 31
</pre>
 
=={{header|Frege}}==
Line 2,878 ⟶ 3,437:
{{Works with|Frege|3.21.586-g026e8d7}}
 
<langsyntaxhighlight lang="frege">module Happy where
 
import Prelude.Math
Line 2,894 ⟶ 3,453:
f = sum . map (sqr . digitToInteger) . unpacked . show
 
main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n</langsyntaxhighlight>
 
{{out}}
Line 2,901 ⟶ 3,460:
1 7 10 13 19 23 28 31
runtime 0.614 wallclock seconds.
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
local fn IsHappy( num as NSUInteger ) as NSUInteger
NSUInteger i, happy = 0, count = 0
while ( count < 50 ) and ( happy != 1 )
CFStringRef numStr = str( num )
count++ : happy = 0
for i = 1 to len( numStr )
happy = happy + fn StringIntegerValue( mid( numStr, i, 1 ) ) ^ 2
next
num = happy
wend
end fn = num
 
void local fn HappyNumbers
NSUInteger i, count = 0
for i = 1 to 100
if ( fn IsHappy(i) == 1 )
count++
NSLog( @"%2lu. %2lu is a happy number", count, i )
if count == 8 then exit fn
end if
next
end fn
 
fn HappyNumbers
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
1. 1 is a happy number
2. 7 is a happy number
3. 10 is a happy number
4. 13 is a happy number
5. 19 is a happy number
6. 23 is a happy number
7. 28 is a happy number
8. 31 is a happy number
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Happy_numbers}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution.'''
 
The following function returns whether a given number is happy or not:
 
[[File:Fōrmulæ - Happy numbers 01.png]]
 
Retrieving the first 8 happy numbers
 
[[File:Fōrmulæ - Happy numbers 02.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Happy numbers 03.png]]
In '''[https://formulae.org/?example=Happy_numbers this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,940 ⟶ 3,552:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,947 ⟶ 3,559:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">Number.metaClass.isHappy = {
def number = delegate as Long
def cycle = new HashSet<Long>()
Line 2,961 ⟶ 3,573:
if (i.happy) { matches << i }
}
println matches</langsyntaxhighlight>
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="xbase">PROCEDURE Main()
LOCAL i := 8, nH := 0
 
Line 2,998 ⟶ 3,610:
AAdd( aUnhappy, nSum )
 
RETURN IsHappy( nSum )</langsyntaxhighlight>
Output:
 
Line 3,005 ⟶ 3,617:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (digitToInt)
import Data.Set (member, insert, empty)
 
Line 3,018 ⟶ 3,630:
 
main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]</langsyntaxhighlight>
{{Out}}
<pre>1
Line 3,030 ⟶ 3,642:
 
We can create a cache for small numbers to greatly speed up the process:
<langsyntaxhighlight lang="haskell">import Data.Array (Array, (!), listArray)
 
happy :: Int -> Bool
Line 3,048 ⟶ 3,660:
 
main :: IO ()
main = print $ sum $ take 10000 $ filter happy [1 ..]</langsyntaxhighlight>
{{Out}}
<pre>327604323</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
local n
n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8
Line 3,069 ⟶ 3,681:
if happy(n) then return i
}
end</langsyntaxhighlight>
Usage and Output:
<pre>
Line 3,078 ⟶ 3,690:
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> 8{. (#~1=+/@(*:@(,.&.":))^:(1&~:*.4&~:)^:_ "0) 1+i.100
1 7 10 13 19 23 28 31</langsyntaxhighlight>
This is a repeat while construction
<langsyntaxhighlight lang="j"> f ^: cond ^: _ input</langsyntaxhighlight>
that produces an array of 1's and 4's, which is converted to 1's and 0's forming a binary array having a 1 for a happy number. Finally the happy numbers are extracted by a binary selector.
<langsyntaxhighlight lang="j"> (binary array) # 1..100</langsyntaxhighlight>
So for easier reading the solution could be expressed as:
<langsyntaxhighlight lang="j"> cond=: 1&~: *. 4&~: NB. not equal to 1 and not equal to 4
sumSqrDigits=: +/@(*:@(,.&.":))
 
Line 3,091 ⟶ 3,703:
14
8{. (#~ 1 = sumSqrDigits ^: cond ^:_ "0) 1 + i.100
1 7 10 13 19 23 28 31</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
{{trans|JavaScript}}
<langsyntaxhighlight lang="java5">import java.util.HashSet;
public class Happy{
public static boolean happy(long number){
Line 3,122 ⟶ 3,734:
}
}
}</langsyntaxhighlight>
Output:
<pre>1
Line 3,137 ⟶ 3,749:
{{works with|Java|1.8}}
{{trans|Java}}
<langsyntaxhighlight lang="java">
 
import java.util.Arrays;
Line 3,164 ⟶ 3,776:
return number == 1;
}
}</langsyntaxhighlight>
Output:
<pre>1
Line 3,179 ⟶ 3,791:
===ES5===
====Iteration====
<langsyntaxhighlight lang="javascript">function happy(number) {
var m, digit ;
var cycle = [] ;
Line 3,204 ⟶ 3,816:
document.write(number + " ") ;
number++ ;
}</langsyntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 3,211 ⟶ 3,823:
====Functional composition====
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// isHappy :: Int -> Bool
Line 3,270 ⟶ 3,882:
take(8, filter(isHappy, enumFromTo(1, 50)))
);
})()</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
Or, to stop immediately at the 8th member of the series, we can preserve functional composition while using an iteratively implemented '''until()''' function:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// isHappy :: Int -> Bool
Line 3,345 ⟶ 3,957:
.xs
);
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def is_happy_number:
def next: tostring | explode | map( (. - 48) | .*.) | add;
def last(g): reduce g as $i (null; $i);
Line 3,365 ⟶ 3,977:
end
end );
1 == last( [.,{}] | loop );</langsyntaxhighlight>
'''Emit a stream of the first n happy numbers''':
<langsyntaxhighlight lang="jq"># Set n to -1 to continue indefinitely:
def happy(n):
def subtask: # state: [i, found]
Line 3,378 ⟶ 3,990:
[0,0] | subtask;
 
happy($n|tonumber)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq --arg n 8 -n -f happy.jq
1
7
Line 3,389 ⟶ 4,001:
28
31
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
function happy(x)
happy_ints = ref(Int)[]
int_try = 1
while length(happy_ints) < x
n = int_try
past = ref(Int)[]
while n != 1
n = sum([y^2 for y in digits(n)])
contains(past,n) ?in breakpast :&& push!(past,n)break
push!(past, n)
end
end
n == 1 && push!(happy_ints,int_try)
int_try += 1
end
return happy_ints
end</langsyntaxhighlight>
Output
<pre> julia> happy(8)
Line 3,420 ⟶ 4,033:
31</pre>
A recursive version:
<langsyntaxhighlight lang="julia">sumhappy(n) = sum(x->x^2, digits(n))
 
function ishappy(x, mem = Int[])
x == 1 ? true :
x in mem ? false :
ishappy(sumhappy(x), [mem ; x])
end
 
nexthappy (x) = ishappy(x+1) ? x+1 : nexthappy(x+1)
happy(n) = accumulate((a, b) -> nexthappy(a), 1:n)
 
</syntaxhighlight>
happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-1]]
</lang>
{{Out}}
<pre>julia> show(happy(8))
Line 3,439 ⟶ 4,051:
Faster with use of cache
{{trans|C}}
<langsyntaxhighlight lang="julia">const CACHE = 256
buf = zeros(Int, CACHE)
buf[1begin] = 1
 
#happy(n) returns 1 if happy, 0 if not
function happy(n)
if n < CACHE
Line 3,448 ⟶ 4,060:
buf[n] = 2
end
sumsqsum = 0
nn = n
while nn != 0
nn, x = divrem(nn%, 10)
sumsqsum += x * x
nn = int8(nn/10)
end
x = happy(sumsqsum)
n < CACHE && (buf[n] = 2 - x)
return x
end
 
function main()
i, counter = 1; counter =, 1000000
while counter > 0
if happy(i) =!= 10
counter -= 1
end
i += 1
end
return i - 1
end</lang>
</syntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> hpy: {x@&1={~|/x=1 4}{_+/_sqr 0$'$x}//:x}
 
hpy 1+!100
Line 3,477 ⟶ 4,090:
 
8#hpy 1+!100
1 7 10 13 19 23 28 31</langsyntaxhighlight>
 
Another implementation which is easy to follow is given below:
<syntaxhighlight lang="k">
<lang K>
/ happynum.k
 
Line 3,490 ⟶ 4,103:
hnum: {[x]; h::();i:1;while[(#h)<x; :[(isHappy i); h::(h,i)]; i+:1]; `0: ,"List of ", ($x), " Happy Numbers"; h}
 
</syntaxhighlight>
</lang>
 
The output of a session with this implementation is given below:
Line 3,505 ⟶ 4,118:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun isHappy(n: Int): Boolean {
Line 3,534 ⟶ 4,147:
}
println("First 8 happy numbers : " + happyNums.joinToString(", "))
}</langsyntaxhighlight>
 
{{out}}
Line 3,540 ⟶ 4,153:
First 8 happy numbers : 1, 7, 10, 13, 19, 23, 28, 31
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def happy
{def happy.sum
{lambda {:n}
{if {= {W.length :n} 1}
then {pow {W.first :n} 2}
else {+ {pow {W.first :n} 2}
{happy.sum {W.rest :n}}}}}}
{def happy.is
{lambda {:x :a}
{if {= :x 1}
then true
else {if {> {A.in? :x :a} -1}
then false
else {happy.is {happy.sum :x}
{A.addlast! :x :a}}}}}}
{def happy.rec
{lambda {:n :a :i}
{if {= {A.length :a} :n}
then :a
else {happy.rec :n
{if {happy.is :i {A.new}}
then {A.addlast! :i :a}
else :a}
{+ :i 1}}}}}
{lambda {:n}
{happy.rec :n {A.new} 0}}}
-> happy
 
{happy 8}
-> [1,7,10,13,19,23,28,31]
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">#!/usr/bin/lasso9
define isHappy(n::integer) => {
Line 3,556 ⟶ 4,203:
where isHappy(#x)
take 8
select #x</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="lasso">1, 7, 10, 13, 19, 23, 28, 31</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<lang lb> ct = 0
n = 0
DO
n = n + 1
IF HappyN(n, sqrInt$) = 1 THEN
ct = ct + 1
PRINT ct, n
END IF
LOOP UNTIL ct = 8
END
 
FUNCTION HappyN(n, sqrInts$)
n$ = Str$(n)
sqrInts = 0
FOR i = 1 TO Len(n$)
sqrInts = sqrInts + Val(Mid$(n$, i, 1)) ^ 2
NEXT i
IF sqrInts = 1 THEN
HappyN = 1
EXIT FUNCTION
END IF
IF Instr(sqrInts$, ":";Str$(sqrInts);":") > 0 THEN
HappyN = 0
EXIT FUNCTION
END IF
sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
HappyN = HappyN(sqrInts, sqrInts$)
END FUNCTION</lang>
Output:-
<pre>1 1
2 7
3 10
4 13
5 19
6 23
7 28
8 31
</pre>
 
=={{header|Locomotive Basic}}==
 
<lang locobasic>10 mode 1:defint a-z
20 for i=1 to 100
30 i2=i
40 for l=1 to 20
50 a$=str$(i2)
60 i2=0
70 for j=1 to len(a$)
80 d=val(mid$(a$,j,1))
90 i2=i2+d*d
100 next j
110 if i2=1 then print i;"is a happy number":n=n+1:goto 150
120 if i2=4 then 150 ' cycle found
130 next l
140 ' check if we have reached 8 numbers yet
150 if n=8 then end
160 next i</lang>
 
[[File:Happy Numbers, Locomotive BASIC.png]]
 
=={{header|Logo}}==
 
<langsyntaxhighlight lang="logo">to sum_of_square_digits :number
output (apply "sum (map [[d] d*d] ` :number))
end
Line 3,646 ⟶ 4,232:
 
print n_happy 8
bye</langsyntaxhighlight>
 
Output:
Line 3,654 ⟶ 4,240:
{{works with|lci 0.10.3}}
 
<langsyntaxhighlight lang="lolcode">OBTW
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
Line 3,736 ⟶ 4,322:
OIC
IM OUTTA YR LOOP
KTHXBYE</langsyntaxhighlight>
 
Output:<pre>1
Line 3,748 ⟶ 4,334:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function digits(n)
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
Line 3,762 ⟶ 4,348:
repeat
i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8</langsyntaxhighlight>
Output:
<pre>1
Line 3,779 ⟶ 4,365:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
Line 3,812 ⟶ 4,398:
PrintHappy=factoryHappy()
Call PrintHappy()
</syntaxhighlight>
</lang>
{{out}}
<pre>
1
7
10
13
19
23
28
31</pre>
 
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE HAPPY
.MCALL .TTYOUT,.EXIT
HAPPY:: MOV #^D8,R5 ; 8 HAPPY NUMBERS
CLR R4
1$: INC R4
MOV R4,R0
JSR PC,CHECK
BNE 1$
MOV R4,R0
JSR PC,PR0
SOB R5,1$
.EXIT
 
; CHECK IF R0 IS HAPPY: ZERO FLAG SET IF TRUE
CHECK: MOV #200,R1
MOV #3$,R2
1$: CLR (R2)+
SOB R1,1$
2$: INCB 3$(R0)
JSR PC,SUMSQ
TST 3$(R0)
BEQ 2$
DEC R0
RTS PC
3$: .BLKW 200
 
; LET R0 = SUM OF SQUARES OF DIGITS OF R0
SUMSQ: CLR R2
1$: MOV #-1,R1
2$: INC R1
SUB #12,R0
BCC 2$
ADD #12,R0
MOVB 3$(R0),R0
ADD R0,R2
MOV R1,R0
BNE 1$
MOV R2,R0
RTS PC
3$: .BYTE ^D 0,^D 1,^D 4,^D 9,^D16
.BYTE ^D25,^D36,^D49,^D64,^D81
 
; PRINT NUMBER IN R0 AS DECIMAL.
PR0: MOV #4$,R1
1$: MOV #-1,R2
2$: INC R2
SUB #12,R0
BCC 2$
ADD #72,R0
MOVB R0,-(R1)
MOV R2,R0
BNE 1$
3$: MOVB (R1)+,R0
.TTYOUT
BNE 3$
RTS PC
.ASCII /...../
4$: .BYTE 15,12,0
.END HAPPY</syntaxhighlight>
{{out}}
<pre>1
7
10
13
Line 3,826 ⟶ 4,482:
=={{header|MAD}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
BOOLEAN CYCLE
DIMENSION CYCLE(200)
Line 3,854 ⟶ 4,510:
END OF PROGRAM
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,869 ⟶ 4,525:
=={{header|Maple}}==
To begin, here is a procedure to compute the sum of the squares of the digits of a positive integer. It uses the built-in procedure irem, which computes the integer remainder and, if passed a name as the optional third argument, assigns it the corresponding quotient. (In other words, it performs integer division with remainder. There is also a dual, companion procedure iquo, which returns the integer quotient and assigns the remainder to the (optional) third argument.)
<langsyntaxhighlight Maplelang="maple">SumSqDigits := proc( n :: posint )
local s := 0;
local m := n;
Line 3,876 ⟶ 4,532:
end do;
s
end proc:</langsyntaxhighlight>
(Note that the unevaluation quotes on the third argument to irem are essential here, as that argument must be a name and, if m were passed without quotes, it would evaluate to a number.)
 
For example,
<syntaxhighlight lang="maple">
<lang Maple>
> SumSqDigits( 1234567890987654321 );
570
</syntaxhighlight>
</lang>
We can check this by computing it another way (more directly).
<syntaxhighlight lang="maple">
<lang Maple>
> n := 1234567890987654321:
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
570
</syntaxhighlight>
</lang>
The most straight-forward way to check whether a number is happy or sad seems also to be the fastest (that I could think of).
<langsyntaxhighlight Maplelang="maple">Happy? := proc( n )
if n = 1 then
true
Line 3,903 ⟶ 4,559:
evalb( s = 1 )
end if
end proc:</langsyntaxhighlight>
We can use this to determine the number of happy (H) and sad (S) numbers up to one million as follows.
<syntaxhighlight lang="maple">
<lang Maple>
> H, S := selectremove( Happy?, [seq]( 1 .. N ) ):
> nops( H ), nops( S );
143071, 856929
</syntaxhighlight>
</lang>
Finally, to solve the stated problem, here is a completely straight-forward routine to locate the first N happy numbers, returning them in a set.
<langsyntaxhighlight Maplelang="maple">FindHappiness := proc( N )
local count := 0;
local T := table();
Line 3,921 ⟶ 4,577:
end do;
{seq}( T[ i ], i = 1 .. count )
end proc:</langsyntaxhighlight>
With input equal to 8, we get
<syntaxhighlight lang="maple">
<lang Maple>
> FindHappiness( 8 );
{1, 7, 10, 13, 19, 23, 28, 31}
</syntaxhighlight>
</lang>
For completeness, here is an implementation of the cycle detection algorithm for recognizing happy numbers. It is much slower, however.
<langsyntaxhighlight Maplelang="maple">Happy? := proc( n :: posint )
local a, b;
a, b := n, SumSqDigits( n );
Line 3,936 ⟶ 4,592:
end do;
evalb( a = 1 )
end proc:</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Custom function HappyQ:
<langsyntaxhighlight Mathematicalang="mathematica">AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]]
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1</langsyntaxhighlight>
Examples for a specific number:
<langsyntaxhighlight Mathematicalang="mathematica">HappyQ[1337]
HappyQ[137]</langsyntaxhighlight>
gives back:
<syntaxhighlight lang="mathematica">True
<lang Mathematica>True
False</langsyntaxhighlight>
Example finding the first 8:
<langsyntaxhighlight Mathematicalang="mathematica">m = 8;
n = 1;
i = 0;
Line 3,961 ⟶ 4,617:
]
]
happynumbers</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{1, 7, 10, 13, 19, 23, 28, 31}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Recursive version:
<langsyntaxhighlight MATLABlang="matlab">function findHappyNumbers
nHappy = 0;
k = 1;
Line 3,988 ⟶ 4,644:
hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]);
end
end</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31 </pre>
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that decomposes te number into a list */
decompose(N) := block(
digits: [],
while N > 0 do
(remainder: mod(N, 10),
digits: cons(remainder, digits),
N: floor(N/10)),
digits
)$
 
/* Function that given a number returns the sum of their digits */
sum_squares_digits(n):=block(
decompose(n),
map(lambda([x],x^2),%%),
apply("+",%%))$
 
/* Predicate function based on the task iterated digits squaring */
happyp(n):=if n=1 then true else if n=89 then false else block(iter:n,while not member(iter,[1,89]) do iter:sum_squares_digits(iter),iter,if iter=1 then true)$
 
/* Test case */
/* First eight happy numbers */
block(
happy:[],i:1,
while length(happy)<8 do (if happyp(i) then happy:endcons(i,happy),i:i+1),
happy);
</syntaxhighlight>
{{out}}
<pre>
[1,7,10,13,19,23,28,31]
</pre>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
fn isHappyNumber n =
(
Line 4,020 ⟶ 4,709:
)
</syntaxhighlight>
</lang>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
1
7
Line 4,031 ⟶ 4,720:
28
31
</syntaxhighlight>
</lang>
 
=={{header|Mercury}}==
<langsyntaxhighlight Mercurylang="mercury">:- module happy.
:- interface.
:- import_module io.
Line 4,073 ⟶ 4,762:
:- func sqr(int) = int.
 
sqr(X) = X * X.</langsyntaxhighlight>
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 4,079 ⟶ 4,768:
=={{header|MiniScript}}==
This solution uses the observation that any infinite cycle of this algorithm hits the number 89, and so that can be used to know when we've found an unhappy number.
<langsyntaxhighlight MiniScriptlang="miniscript">isHappy = function(x)
while true
if x == 89 then return false
Line 4,098 ⟶ 4,787:
i = i + 1
end while
print "First 8 happy numbers: " + found</langsyntaxhighlight>
{{out}}
<pre>First 8 happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map show (take 8 happynumbers)))]
 
happynumbers :: [num]
happynumbers = filter ishappy [1..]
 
ishappy :: num->bool
ishappy n = 1 $in loop (iterate sumdigitsquares n)
 
sumdigitsquares :: num->num
sumdigitsquares 0 = 0
sumdigitsquares n = (n mod 10)^2 + sumdigitsquares (n div 10)
 
loop :: [*]->[*]
loop = loop' []
where loop' mem (a:as) = mem, if a $in mem
= loop' (a:mem) as, otherwise
 
in :: *->[*]->bool
in val [] = False
in val (a:as) = True, if a=val
= val $in as, otherwise</syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
28
31</pre>
 
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">(*
A happy number is defined by the following process. Starting with any positive integer, replace the number
by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will
Line 4,139 ⟶ 4,861:
 
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
</syntaxhighlight>
</lang>
Output:
<pre>1 is happy
Line 4,153 ⟶ 4,875:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE HappyNumbers;
FROM InOut IMPORT WriteCard, WriteLn;
 
Line 4,196 ⟶ 4,918:
INC(num);
END;
END HappyNumbers.</langsyntaxhighlight>
{{out}}
<pre> 1
Line 4,208 ⟶ 4,930:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">ISHAPPY(N)
;Determines if a number N is a happy number
;Note that the returned strings do not have a leading digit unless it is a happy number
Line 4,231 ⟶ 4,953:
FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
KILL I
QUIT</langsyntaxhighlight>
Output:<pre>
USER>D HAPPY^ROSETTA(8)
Line 4,253 ⟶ 4,975:
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="netrexx">/*NetRexx program to display the 1st 8 (or specified arg) happy numbers*/
limit = arg[0] /*get argument for LIMIT. */
say limit
Line 4,280 ⟶ 5,002:
q=sum /*now, lets try the Q sum. */
end
end</langsyntaxhighlight>
;Output
<pre>
Line 4,398 ⟶ 5,120:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import intsets
 
proc happy(n: int): bool =
Line 4,417 ⟶ 5,139:
for x in 0..31:
if happy(x):
echo x</langsyntaxhighlight>
Output:
<pre>1
Line 4,429 ⟶ 5,151:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
use Structure;
 
Line 4,475 ⟶ 5,197:
}
}
}</langsyntaxhighlight>
output:
<pre>First 8 happy numbers: 1,7,10,13,19,23,28,31,</pre>
Line 4,481 ⟶ 5,203:
=={{header|OCaml}}==
Using [[wp:Cycle detection|Floyd's cycle-finding algorithm]].
<langsyntaxhighlight lang="ocaml">open Num
 
let step =
Line 4,505 ⟶ 5,227:
 
List.iter print_endline (
List.rev_map string_of_num (first 8)) ;;</langsyntaxhighlight>
Output:
<pre>$ ocaml nums.cma happy_numbers.ml
Line 4,519 ⟶ 5,241:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: isHappy(n)
| cycle |
ListBuffer new ->cycle
Line 4,534 ⟶ 5,256:
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;</langsyntaxhighlight>
 
Output:
Line 4,540 ⟶ 5,262:
>happyNum(8)
[1, 7, 10, 13, 19, 23, 28, 31]
</pre>
 
=={{header|Ol}}==
<syntaxhighlight lang="Scheme">
(define (number->list num)
(let loop ((num num) (lst #null))
(if (zero? num)
lst
(loop (quotient num 10) (cons (remainder num 10) lst)))))
 
(define (** x) (* x x))
 
(define (happy? num)
(let loop ((num num) (seen #null))
(cond
((= num 1) #true)
((memv num seen) #false)
(else
(loop (apply + (map ** (number->list num)))
(cons num seen))))))
 
(display "happy numbers: ")
(let loop ((n 1) (count 0))
(unless (= count 8)
(if (happy? n)
then
(display n) (display " ")
(loop (+ n 1) (+ count 1))
else
(loop (+ n 1) count))))
(print)
</syntaxhighlight>
<pre>
happy numbers: 1 7 10 13 19 23 28 31
</pre>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
count = 0
say "First 8 happy numbers are:"
Line 4,572 ⟶ 5,328:
number = next
end
</syntaxhighlight>
</lang>
<pre>
First 8 happy numbers are:
Line 4,586 ⟶ 5,342:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">functor
import
System
Line 4,629 ⟶ 5,385:
in
{System.show {List.take HappyNumbers 8}}
end</langsyntaxhighlight>
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Line 4,636 ⟶ 5,392:
{{PARI/GP select}}
If the number has more than three digits, the sum of the squares of its digits has fewer digits than the number itself. If the number has three digits, the sum of the squares of its digits is at most 3 * 9^2 = 243. A simple solution is to look up numbers up to 243 and calculate the sum of squares only for larger numbers.
<langsyntaxhighlight lang="parigp">H=[1,7,10,13,19,23,28,31,32,44,49,68,70,79,82,86,91,94,97,100,103,109,129,130,133,139,167,176,188,190,192,193,203,208,219,226,230,236,239];
isHappy(n)={
if(n<262,
Line 4,645 ⟶ 5,401:
)
};
select(isHappy, vector(31,i,i))</langsyntaxhighlight>
Output:
<pre>%1 = [1, 7, 10, 13, 19, 23, 28, 31]</pre>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program HappyNumbers (output);
 
uses
Line 4,710 ⟶ 5,466:
end;
writeln;
end.</langsyntaxhighlight>
Output:
<pre>:> ./HappyNumbers
Line 4,721 ⟶ 5,477:
Extended to 10e18
Tested with Free Pascal 3.0.4
<langsyntaxhighlight lang="pascal">Program HappyNumbers (output);
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,970 ⟶ 5,726:
writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0));
end.
</syntaxhighlight>
</lang>
;output:
<pre>
Line 5,022 ⟶ 5,778:
=={{header|Perl}}==
Since all recurrences end with 1 or repeat (37,58,89,145,42,20,4,16), we can do this test very quickly without having to make hashes of seen numbers.
<langsyntaxhighlight lang="perl">use List::Util qw(sum);
 
sub ishappy {
Line 5,033 ⟶ 5,789:
 
my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n";</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,039 ⟶ 5,795:
Or we can solve using only the rudimentary task knowledge as below. Note the slightly different ways of doing the digit sum and finding the first 8 numbers where ishappy(n) is true -- this shows there's more than one way to do even these small sub-tasks.
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use List::Util qw(sum);
sub is_happy {
my ($n) = @_;
Line 5,051 ⟶ 5,807:
 
my $n;
is_happy( ++$n ) and print "$n " or redo for 1..8;</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,057 ⟶ 5,813:
=={{header|Phix}}==
Copy of [[Happy_numbers#Euphoria|Euphoria]] tweaked to give a one-line output
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">is_happy</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">seen</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 5,084 ⟶ 5,840:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,092 ⟶ 5,848:
=={{header|PHP}}==
{{trans|D}}
<langsyntaxhighlight lang="php">function isHappy($n) {
while (1) {
$total = 0;
Line 5,115 ⟶ 5,871:
}
$i++;
}</langsyntaxhighlight>
<pre>1 7 10 13 19 23 28 31 </pre>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
println(happy_len(8)).
 
Line 5,143 ⟶ 5,899:
end,
N := N + 1
end.</langsyntaxhighlight>
 
{{out}}
Line 5,149 ⟶ 5,905:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de happy? (N)
(let Seen NIL
(loop
Line 5,161 ⟶ 5,917:
(do 8
(until (happy? (inc 'H)))
(printsp H) ) )</langsyntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31</pre>
 
=={{header|PILOT}}==
<langsyntaxhighlight lang="pilot">C :max=8
:n=0
:i=0
Line 5,202 ⟶ 5,958:
:x=y
J (x):*digit
E :</langsyntaxhighlight>
{{out}}
<pre>1
Line 5,214 ⟶ 5,970:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">test: proc options (main); /* 19 November 2011 */
declare (i, j, n, m, nh initial (0) ) fixed binary (31);
 
Line 5,238 ⟶ 5,994:
end;
end test;
</syntaxhighlight>
</lang>
OUTPUT:
<pre>
Line 5,252 ⟶ 6,008:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
 
/* FIND SUM OF SQUARE OF DIGITS OF NUMBER */
Line 5,322 ⟶ 6,078:
 
CALL BDOS(0,0);
EOF</langsyntaxhighlight>
{{out}}
<pre>1
Line 5,334 ⟶ 6,090:
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">sqr = (n): n * n.
 
isHappy = (n) :
Line 5,353 ⟶ 6,109:
if (isHappy(i)): firstEight append(i).
.
firstEight string print</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">function happy([int] $n) {
$a=@()
for($i=2;$a.count -lt $n;$i++) {
Line 5,375 ⟶ 6,131:
}
$a -join ','
}</langsyntaxhighlight>
Output :
<langsyntaxhighlight PowerShelllang="powershell">happy(8)
7,10,13,19,23,28,31,32</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<langsyntaxhighlight Prologlang="prolog">happy_numbers(L, Nb) :-
% creation of the list
length(L, Nb),
Line 5,428 ⟶ 6,184:
 
square(N, SN) :-
SN is N * N.</langsyntaxhighlight>
Output :
<langsyntaxhighlight Prologlang="prolog"> ?- happy_numbers(L, 8).
L = [1,7,10,13,19,23,28,31].</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<lang PureBasic>#ToFind=8
#MaxTests=100
#True = 1: #False = 0
Declare is_happy(n)
 
If OpenConsole()
Define i=1,Happy
Repeat
If is_happy(i)
Happy+1
PrintN("#"+Str(Happy)+RSet(Str(i),3))
EndIf
i+1
Until Happy>=#ToFind
;
Print(#CRLF$+#CRLF$+"Press ENTER to exit"): Input()
CloseConsole()
EndIf
 
Procedure is_happy(n)
Protected i,j=n,dig,sum
Repeat
sum=0
While j
dig=j%10
j/10
sum+dig*dig
Wend
If sum=1: ProcedureReturn #True: EndIf
j=sum
i+1
Until i>#MaxTests
ProcedureReturn #False
EndProcedure</lang>
Sample output:
<pre>#1 1
#2 7
#3 10
#4 13
#5 19
#6 23
#7 28
#8 31</pre>
 
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def happy(n):
past = set()
while n != 1:
Line 5,490 ⟶ 6,201:
 
>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
===Composition of pure functions===
 
Drawing 8 terms from a non finite stream, rather than assuming prior knowledge of the finite sample size required:
<langsyntaxhighlight lang="python">'''Happy numbers'''
 
from itertools import islice
Line 5,573 ⟶ 6,284:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 5,579 ⟶ 6,290:
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">
<lang Quackery>
[ 0 swap
[ 10 /mod 2 **
Line 5,601 ⟶ 6,312:
drop nip ] is happies ( n --> [ )
 
8 happies echo</langsyntaxhighlight>
 
{{Out}}
Line 5,608 ⟶ 6,319:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">is.happy <- function(n)
{
stopifnot(is.numeric(n) && length(n)==1)
Line 5,636 ⟶ 6,347:
}
happy
}</langsyntaxhighlight>
Example usage
<syntaxhighlight lang R="r">is.happy(2)</langsyntaxhighlight>
[1] FALSE
attr(,"cycle")
[1] 4 16 37 58 89 145 42 20
<langsyntaxhighlight Rlang="r">#Find happy numbers between 1 and 50
which(apply(rbind(1:50), 2, is.happy))</langsyntaxhighlight>
1 7 10 13 19 23 28 31 32 44 49
<langsyntaxhighlight Rlang="r">#Find the first 8 happy numbers
happies <- c()
i <- 1L
Line 5,653 ⟶ 6,364:
i <- i + 1L
}
happies</langsyntaxhighlight>
1 7 10 13 19 23 28 31
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
Line 5,678 ⟶ 6,389:
x))
 
(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-13}}
<syntaxhighlight lang="raku" perl6line>sub happy (Int $n is copy --> Bool) {
loop {
state %seen;
Line 5,692 ⟶ 6,403:
}
 
say join ' ', grep(&happy, 1 .. *)[^8];</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Here's another approach that uses a different set of tricks including lazy lists, gather/take, repeat-until, and the cross metaoperator X.
<syntaxhighlight lang="raku" perl6line>my @happy = lazy gather for 1..* -> $number {
my %stopper = 1 => 1;
my $n = $number;
Line 5,705 ⟶ 6,416:
}
 
say ~@happy[^8];</langsyntaxhighlight>
Output is the same as above.
 
Here is a version using a subset and an anonymous recursion (we cheat a little bit by using the knowledge that 7 is the second happy number):
<syntaxhighlight lang="raku" perl6line>subset Happy of Int where sub ($n) {
$n == 1 ?? True !!
$n < 7 ?? False !!
Line 5,715 ⟶ 6,426:
}
say (grep Happy, 1 .. *)[^8];</langsyntaxhighlight>
Again, output is the same as above. It is not clear whether this version returns in finite time for any integer, though.
 
There's more than one way to do it...
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <ShowFirst 8 Happy 1>;
};
 
ShowFirst {
0 s.F s.I = ;
s.N s.F s.I, <Mu s.F s.I>: T =
<Prout s.I>
<ShowFirst <- s.N 1> s.F <+ s.I 1>>;
s.N s.F s.I =
<ShowFirst s.N s.F <+ s.I 1>>;
};
 
Happy {
1 e.X = T;
s.N e.X s.N e.Y = F;
s.N e.X = <Happy <SqDigSum s.N> s.N e.X>;
};
 
SqDigSum {
0 = 0;
s.N, <Symb s.N>: s.Ds e.Rs,
<Numb s.Ds>: s.D,
<Numb e.Rs>: s.R =
<+ <* s.D s.D> <SqDigSum s.R>>;
};</syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
28
31</pre>
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
<lang Relation>
function happy(x)
set y = x
Line 5,753 ⟶ 6,501:
set i = i + 1
end while
</syntaxhighlight>
</lang>
 
<pre>
Line 5,767 ⟶ 6,515:
 
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program computes and displays a specified range of happy numbers. */
===unoptimized===
Call time 'R'
<lang REXX>/*REXX program computes and displays a specified amount of happy numbers. */
linesize=80
parse arg limit . /*obtain optional argument from the CL.*/
Parse Arg low high /* obtain range of happy numbers */
if limit=='' | limit=="," then limit=8 /*Not specified? Then use the default.*/
If low='?' Then Call help
haps=0 /*count of the happy numbers (so far).*/
If low='' Then low=10
If high='' Then
Parse Value 1 low With low high
Do i=0 To 9 /*build a squared decimal digit table. */
square.i=i*i
End
happy.=0 /* happy.m=1 - m is a happy number */
unhappy.=0 /* unhappy.n=1 - n is an unhappy number*/
hapn=0 /* count of the happy numbers */
ol=''
Do n=1 While hapn<high /* test integers starting with 1 */
If unhappy.n Then /* if n is unhappy, */
Iterate /* then try next number */
work=n
suml='' /* list of computed sums */
Do Forever
sum=0
Do length(work) /* compute sum of squared digits */
Parse Var work digit +1 work
sum=sum+square.digit
End
Select
When unhappy.sum |, /* sum is known to be unhappy */
wordpos(sum,suml)>0 Then Do /* or was already encountered */
-- If wordpos(sum,suml)>0 Then say 'Loop' n':' suml sum
-- If n<7 Then say n':' suml sum
unhappy.n=1 /* n is unhappy */
Call set suml /* amd so are all sums so far */
Iterate n
End
When sum=1 Then Do /* we reached sum=1 */
hapn+=1 /* increment number of happy numbers */
happy.n=1 /* n is happy */
If hapn>=low Then /* if it is in specified range */
Call out n /* output it */
If hapn=high Then /* end of range reached */
Leave n /* we are done */
Iterate n /* otherwise proceed */
End
Otherwise Do /* otherwise */
suml=suml sum /* add sum to list of sums */
work=sum /* proceed with the new sum */
End
End
End
End
If ol>'' Then /* more output data */
Say strip(ol) /* write to console */
-- Say time('E')
Exit
 
set: do n=1 while haps<limit; @.=0; q=n /*search theall intermediate sums are integersunhappy starting at unity*/
Parse Arg list
do until q==1 /*determine if Q is a happy number.*/
Do While list<>''
s=0 /*prepare to add squares of digits. */
Parse Var list s list
do j=1 for length(q) /*sum the squares of the decimal digits*/
unhappy.s=1
s=s + substr(q, j, 1) **2 /*add the square of a decimal digit.*/
End
end /*j*/
Return
 
out: if @.s then iterate n /*if alreadyoutput management summed, Q is unhappy. */
Parse Arg hn @.s=1; q=s /* the happy number /*mark the sum as found; try Q sum.*/
If length(ol hn)>linesize Then Do /* if it does not fit */
end /*until*/
say n Say strip(ol) /* output the line /*display the number (N is happy). */
haps=haps+1 ol=hn /*bump theand start a new line count of happy numbers. */
End
end /*n*/
Else /* otherwise /*stick a fork in it, we're all done. */</lang>
ol=ol hn /* append is to the output line */
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 8 </tt>}}
Return
<pre>
1
7
10
13
19
23
28
31
</pre>
 
help:
===optimized, vertical list===
This REXX codeSay uses'rexx additionalhno memorizationn (bycompute keepingand trackshow ofthe happyfirst andn unhappyhappy numbers),'
Say 'rexx hno low high show happy numbers from index low to high'
<br>it's about &nbsp; 2 <sup>1</sup>/<sub>2</sub> &nbsp; times faster than the unoptimized version.
Exit
<br><br>This REXX version also accepts a &nbsp; ''range'' &nbsp; of happy numbers to be shown, &nbsp; that is,
</syntaxhighlight>
<br>it can show the 2000<sup>th</sup> through the 2032<sup>nd</sup> (inclusive) happy numbers &nbsp; (as shown below).
{{out}}
<lang rexx>/*REXX program computes and displays a specified range of happy numbers. */
parse arg L H . /*obtain optional arguments from the CL*/
if L=='' | L=="," then L=8 /*Not specified? Then use the default.*/
if H=='' | H=="," then do; H=L; L=1; end /*use a range for the displaying of #s.*/
do i=0 to 9; #.i=i**2; end /*i*/ /*build a squared decimal digit table. */
@.=0; @.1=1; !.=@.; !.2=1; !.4=1 /*sparse array: @≡happy, !≡unhappy. */
haps=0 /*count of the happy numbers (so far).*/
 
do n=1 while haps<H /*search integers starting at unity. */
if !.n then iterate /*if N is unhappy, then try another. */
q=n /* [↓] Q is the number being tested*/
do until q==1; s=0 /*see if Q is a happy number. */
?=q /* [↓] ? is destructively parsed. */
do length(q) /*parse all the decimal digits of ? */
parse var ? _ +1 ? /*obtain a single decimal digit of ? */
s=s + #._ /*add the square of that decimal digit.*/
end /*length(q)*/ /* [↑] perform the DO W times. */
if !.s then do; !.n=1; iterate n; end /*is S unhappy? Then Q is also. */
if @.s then leave /*Have we found a happy number? */
q=s /*try the Q sum to see if it's happy.*/
end /*until*/
@.n=1 /*mark N as a happy number.*/
haps=haps+1 /*bump the counter of the happy numbers*/
if haps<L then iterate /*don't display if N is too low.*/
say right(n, 30) /*display right justified happy number.*/
end /*n*/
/*stick a fork in it, we're all done. */</lang>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 2000 &nbsp; 2032 </tt>}}
<pre>
K:\_B\HN>rexx hno ?
13141
rexx hno n compute and show the first n happy numbers
13142
rexx hno low high show happy numbers from index low to 13148high
13158
13177
13182
13184
13185
13188
13203
13212
13214
13218
13221
13228
13230
13233
13241
13247
13248
13258
13266
13274
13281
13282
13284
13285
13299
13300
13302
13303
13305
13307
</pre>
 
K:\_B\HN>rexx hno 8
===optimized, horizontal list===
1 7 10 13 19 23 28 31
This REXX version is identical to the optimized version, &nbsp; but displays the numbers in a horizontal list.
<lang rexx>/*REXX program computes and displays a specified range of happy numbers. */
sw=linesize() - 1 /*obtain the screen width (less one). */
parse arg limit . /*obtain optional argument from the CL.*/
if L=='' | L=="," then L=8 /*Not specified? Then use the default.*/
if H=='' | H=="," then do; H=L; L=1; end /*use a range for the displaying of #s.*/
do i=0 to 9; #.i=i**2; end /*i*/ /*build a squared decimal digit table. */
@.=0; @.1=1; !.=@.; !.2=1; !.4=1 /*sparse array: @≡happy, !≡unhappy. */
haps=0 /*count of the happy numbers (so far).*/
$=
do n=1 while haps<H /*search integers starting at unity. */
if !.n then iterate /*if N is unhappy, then try another. */
q=n /*(below) Q is the number tested. */
do until q==1; s=0 /*see if Q is a happy number. */
?=q /* [↓] ? is destructively PARSEd. */
do length(q) /*parse all the decimal digits of ? */
parse var ? _ +1 ? /*obtain a single decimal digit of ? */
s=s + #._ /*add the square of that decimal digit.*/
end /*length(q)*/ /* [↑] perform the DO W times. */
 
if !.s then do; !.n=1; iterate n; end /*is S unhappy? Then Q is also. */
if @.s then leave /*Have we found a happy number? */
q=s /*try the Q sum to see if it's happy.*/
end /*until*/
@.n=1 /*mark N as a happy number. */
haps=haps+1 /*bump the count of the happy numbers. */
if haps<L then iterate /*don't display it, N is too low. */
$=$ n /*add N to the horizontal list. */
if length($ n)>sw then do /*if the list is too long, then split */
say strip($) /* ··· and display what we've got. */
$=n /*Set the next line to overflow. */
end /* [↑] new line now contains overflow.*/
end /*n*/
if $\='' then say strip($) /*display any residual happy numbers. */
/*stick a fork in it, we're all done. */</lang>
This REXX program makes use of &nbsp; '''linesize''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
 
Some REXXes don't have this BIF, so the &nbsp; '''linesize.rex''' &nbsp; REXX program is included here &nbsp; ──► &nbsp; [[LINESIZE.REX]]. <br>
 
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 1 &nbsp; 15002 </tt>}}
 
(The &nbsp; ''linesize'' &nbsp; for the terminal being used for this example was &nbsp; 200.)
 
K:\_B\HN>rexx hno 1000 1003
<br>(Shown at two-thirds size.)
6899 6904 6917 6923
<b>
<pre style="font-size:67%">
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 103 109 129 130 133 139 167 176 188 190 192 193 203 208 219 226 230 236 239 262 263 280 291 293 301 302 310 313 319 320 326 329 331 338 356
362 365 367 368 376 379 383 386 391 392 397 404 409 440 446 464 469 478 487 490 496 536 556 563 565 566 608 617 622 623 632 635 637 638 644 649 653 655 656 665 671 673 680 683 694 700 709 716 736 739
748 761 763 784 790 793 802 806 818 820 833 836 847 860 863 874 881 888 899 901 904 907 910 912 913 921 923 931 932 937 940 946 964 970 973 989 998 1000 1003 1009 1029 1030 1033 1039 1067 1076 1088
1090 1092 1093 1112 1114 1115 1121 1122 1125 1128 1141 1148 1151 1152 1158 1177 1182 1184 1185 1188 1209 1211 1212 1215 1218 1221 1222 1233 1247 1251 1257 1258 1274 1275 1277 1281 1285 1288 1290 1299
1300 1303 1309 1323 1330 1332 1333 1335 1337 1339 1353 1366 1373 1390 1393 1411 1418 1427 1444 1447 1448 1457 1472 1474 1475 1478 1481 1484 1487 1511 1512 1518 1521 1527 1528 1533 1547 1557 1572 1574
1575 1578 1581 1582 1587 1599 1607 1636 1663 1666 1670 1679 1697 1706 1717 1724 1725 1727 1733 1742 1744 1745 1748 1752 1754 1755 1758 1760 1769 1771 1772 1784 1785 1796 1808 1812 1814 1815 1818 1821
1825 1828 1841 1844 1847 1851 1852 1857 1874 1875 1880 1881 1882 1888 1900 1902 1903 1920 1929 1930 1933 1959 1967 1976 1992 1995 2003 2008 2019 2026 2030 2036 2039 2062 2063 2080 2091 2093 2109 2111
2112 2115 2118 2121 2122 2133 2147 2151 2157 2158 2174 2175 2177 2181 2185 2188 2190 2199 2206 2211 2212 2221 2224 2242 2245 2254 2257 2258 2260 2275 2285 2300 2306 2309 2313 2331 2333 2338 2339 2360
2369 2383 2390 2393 2396 2417 2422 2425 2448 2452 2455 2457 2458 2471 2475 2478 2484 2485 2487 2511 2517 2518 2524 2527 2528 2542 2545 2547 2548 2554 2555 2557 2568 2571 2572 2574 2575 2581 2582 2584
2586 2602 2603 2620 2630 2639 2658 2685 2693 2714 2715 2717 2725 2741 2745 2748 2751 2752 2754 2755 2771 2784 2800 2811 2815 2818 2825 2833 2844 2845 2847 2851 2852 2854 2856 2865 2874 2881 2899 2901
2903 2910 2919 2930 2933 2936 2963 2989 2991 2998 3001 3002 3010 3013 3019 3020 3026 3029 3031 3038 3056 3062 3065 3067 3068 3076 3079 3083 3086 3091 3092 3097 3100 3103 3109 3123 3130 3132 3133 3135
3137 3139 3153 3166 3173 3190 3193 3200 3206 3209 3213 3231 3233 3238 3239 3260 3269 3283 3290 3293 3296 3301 3308 3310 3312 3313 3315 3317 3319 3321 3323 3328 3329 3331 3332 3338 3346 3351 3355 3356
3364 3365 3367 3371 3376 3380 3382 3383 3391 3392 3436 3456 3463 3465 3466 3506 3513 3531 3535 3536 3546 3553 3560 3563 3564 3602 3605 3607 3608 3616 3620 3629 3634 3635 3637 3643 3645 3646 3650 3653
3654 3661 3664 3667 3670 3673 3676 3680 3689 3692 3698 3706 3709 3713 3731 3736 3760 3763 3766 3779 3789 3790 3797 3798 3803 3806 3823 3830 3832 3833 3860 3869 3879 3896 3897 3901 3902 3907 3910 3913
3920 3923 3926 3931 3932 3962 3968 3970 3977 3978 3986 3987 4004 4009 4040 4046 4064 4069 4078 4087 4090 4096 4111 4118 4127 4144 4147 4148 4157 4172 4174 4175 4178 4181 4184 4187 4217 4222 4225 4248
4252 4255 4257 4258 4271 4275 4278 4284 4285 4287 4336 4356 4363 4365 4366 4400 4406 4414 4417 4418 4428 4441 4447 4449 4455 4460 4471 4474 4477 4481 4482 4494 4517 4522 4525 4527 4528 4536 4545 4552
4554 4555 4558 4563 4571 4572 4577 4582 4585 4599 4604 4609 4633 4635 4636 4640 4653 4663 4690 4708 4712 4714 4715 4718 4721 4725 4728 4741 4744 4747 4751 4752 4757 4774 4775 4780 4781 4782 4788 4807
4811 4814 4817 4824 4825 4827 4841 4842 4852 4855 4870 4871 4872 4878 4887 4888 4900 4906 4944 4959 4960 4995 5036 5056 5063 5065 5066 5111 5112 5118 5121 5127 5128 5133 5147 5157 5172 5174 5175 5178
5181 5182 5187 5199 5211 5217 5218 5224 5227 5228 5242 5245 5247 5248 5254 5255 5257 5268 5271 5272 5274 5275 5281 5282 5284 5286 5306 5313 5331 5335 5336 5346 5353 5360 5363 5364 5417 5422 5425 5427
5428 5436 5445 5452 5454 5455 5458 5463 5471 5472 5477 5482 5485 5499 5506 5517 5524 5525 5527 5533 5542 5544 5545 5548 5552 5554 5555 5558 5560 5569 5571 5572 5584 5585 5596 5603 5605 5606 5628 5630
5633 5634 5643 5650 5659 5660 5666 5682 5695 5712 5714 5715 5718 5721 5722 5724 5725 5741 5742 5747 5751 5752 5774 5781 5789 5798 5799 5811 5812 5817 5821 5822 5824 5826 5842 5845 5854 5855 5862 5871
5879 5897 5919 5949 5956 5965 5978 5979 5987 5991 5994 5997 6008 6017 6022 6023 6032 6035 6037 6038 6044 6049 6053 6055 6056 6065 6071 6073 6080 6083 6094 6107 6136 6163 6166 6170 6179 6197 6202 6203
6220 6230 6239 6258 6285 6293 6302 6305 6307 6308 6316 6320 6329 6334 6335 6337 6343 6345 6346 6350 6353 6354 6361 6364 6367 6370 6373 6376 6380 6389 6392 6398 6404 6409 6433 6435 6436 6440 6453 6463
6490 6503 6505 6506 6528 6530 6533 6534 6543 6550 6559 6560 6566 6582 6595 6605 6613 6616 6631 6634 6637 6643 6650 6656 6661 6665 6673 6701 6703 6710 6719 6730 6733 6736 6763 6789 6791 6798 6800 6803
6825 6830 6839 6852 6879 6893 6897 6899 6904 6917 6923 6932 6938 6940 6955 6971 6978 6983 6987 6989 6998 7000 7009 7016 7036 7039 7048 7061 7063 7084 7090 7093 7106 7117 7124 7125 7127 7133 7142 7144
7145 7148 7152 7154 7155 7158 7160 7169 7171 7172 7184 7185 7196 7214 7215 7217 7225 7241 7245 7248 7251 7252 7254 7255 7271 7284 7306 7309 7313 7331 7336 7360 7363 7366 7379 7389 7390 7397 7398 7408
7412 7414 7415 7418 7421 7425 7428 7441 7444 7447 7451 7452 7457 7474 7475 7480 7481 7482 7488 7512 7514 7515 7518 7521 7522 7524 7525 7541 7542 7547 7551 7552 7574 7581 7589 7598 7599 7601 7603 7610
7619 7630 7633 7636 7663 7689 7691 7698 7711 7712 7721 7739 7744 7745 7754 7788 7793 7804 7814 7815 7824 7839 7840 7841 7842 7848 7851 7859 7869 7878 7884 7887 7893 7895 7896 7900 7903 7916 7930 7937
7938 7958 7959 7961 7968 7973 7983 7985 7986 7995 8002 8006 8018 8020 8033 8036 8047 8060 8063 8074 8081 8088 8099 8108 8112 8114 8115 8118 8121 8125 8128 8141 8144 8147 8151 8152 8157 8174 8175 8180
8181 8182 8188 8200 8211 8215 8218 8225 8233 8244 8245 8247 8251 8252 8254 8256 8265 8274 8281 8299 8303 8306 8323 8330 8332 8333 8360 8369 8379 8396 8397 8407 8411 8414 8417 8424 8425 8427 8441 8442
8452 8455 8470 8471 8472 8478 8487 8488 8511 8512 8517 8521 8522 8524 8526 8542 8545 8554 8555 8562 8571 8579 8597 8600 8603 8625 8630 8639 8652 8679 8693 8697 8699 8704 8714 8715 8724 8739 8740 8741
8742 8748 8751 8759 8769 8778 8784 8787 8793 8795 8796 8801 8808 8810 8811 8812 8818 8821 8847 8848 8874 8877 8880 8881 8884 8909 8929 8936 8937 8957 8963 8967 8969 8973 8975 8976 8990 8992 8996 9001
9004 9007 9010 9012 9013 9021 9023 9031 9032 9037 9040 9046 9064 9070 9073 9089 9098 9100 9102 9103 9120 9129 9130 9133 9159 9167 9176 9192 9195 9201 9203 9210 9219 9230 9233 9236 9263 9289 9291 9298
9301 9302 9307 9310 9313 9320 9323 9326 9331 9332 9362 9368 9370 9377 9378 9386 9387 9400 9406 9444 9459 9460 9495 9519 9549 9556 9565 9578 9579 9587 9591 9594 9597 9604 9617 9623 9632 9638 9640 9655
9671 9678 9683 9687 9689 9698 9700 9703 9716 9730 9737 9738 9758 9759 9761 9768 9773 9783 9785 9786 9795 9809 9829 9836 9837 9857 9863 9867 9869 9873 9875 9876 9890 9892 9896 9908 9912 9915 9921 9928
9945 9951 9954 9957 9968 9975 9980 9982 9986 10000 10003 10009 10029 10030 10033 10039 10067 10076 10088 10090 10092 10093 10112 10114 10115 10121 10122 10125 10128 10141 10148 10151 10152 10158
10177 10182 10184 10185 10188 10209 10211 10212 10215 10218 10221 10222 10233 10247 10251 10257 10258 10274 10275 10277 10281 10285 10288 10290 10299 10300 10303 10309 10323 10330 10332 10333 10335
10337
</pre>
</b>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">n = 1
found = 0
Line 5,981 ⟶ 6,632:
End
Return True
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,994 ⟶ 6,645:
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
≪ { } SWAP '''DO'''
SWAP OVER + 0 ROT
'''DO'''
MANT RND DUP IP SQ ROT + SWAP FP
'''UNTIL''' DUP NOT '''END'''
DROP
'''UNTIL''' DUP2 POS '''END'''
SWAP DROP 1 ==
'HAPY?' STO
≪ { } 0 '''DO'''
1 + '''IF''' DUP HAPY? '''THEN''' SWAP OVER + SWAP '''END'''
'''UNTIL''' OVER SIZE 8 == '''END'''
≫ EVAL
{{out}}
<pre>
1: { 1 7 10 13 19 23 28 31 }
</pre>
=={{header|Ruby}}==
{{works with|Ruby|2.1}}
 
<langsyntaxhighlight lang="ruby">require 'set' # Set: Fast array lookup / Simple existence hash
 
@seen_numbers = Set.new
Line 6,007 ⟶ 6,679:
 
@seen_numbers << n
digit_squared_sum = n.to_sdigits.each_char.inject(0) sum{ |sum, cn| sum + c.to_in**2 } # In Rails: n.to_s.each_char.sum { c.to_i**2 }
 
if happy?(digit_squared_sum)
Line 6,015 ⟶ 6,687:
false # Return false
end
end</langsyntaxhighlight>
 
Helper method to produce output:
<langsyntaxhighlight lang="ruby">def print_happy
happy_numbers = []
 
Line 6,029 ⟶ 6,701:
end
 
print_happy</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="ruby">[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
===Alternative version===
<langsyntaxhighlight lang="ruby">@memo = [0,1]
def happy(n)
sum = n.to_sdigits.chars.mapsum{|cn| c.to_in**2n}.inject(:+)
return @memo[sum] if @memo[sum]==0 or @memo[sum]==1
@memo[sum] = 0 # for the cycle check
Line 6,052 ⟶ 6,724:
for i in 99999999999900..99999999999999
puts i if happy(i)==1
end</langsyntaxhighlight>
 
{{out}}
Line 6,081 ⟶ 6,753:
===Simpler Alternative===
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def happy?(n)
past = []
until n == 1
Line 6,094 ⟶ 6,766:
until count == 8; puts i or count += 1 if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</langsyntaxhighlight>
{{out}}
<pre>
Line 6,118 ⟶ 6,790:
99999999999965
99999999999973</pre>
 
=={{header|Run BASIC}}==
<lang runbasic>for i = 1 to 100
if happy(i) = 1 then
cnt = cnt + 1
PRINT cnt;". ";i;" is a happy number "
if cnt = 8 then end
end if
next i
FUNCTION happy(num)
while count < 50 and happy <> 1
num$ = str$(num)
count = count + 1
happy = 0
for i = 1 to len(num$)
happy = happy + val(mid$(num$,i,1)) ^ 2
next i
num = happy
wend
end function</lang>
<pre>1. 1 is a happy number
2. 7 is a happy number
3. 10 is a happy number
4. 13 is a happy number
5. 19 is a happy number
6. 23 is a happy number
7. 28 is a happy number
8. 31 is a happy number
</pre>
 
=={{header|Rust}}==
In Rust, using a tortoise/hare cycle detection algorithm (generic for integer types)
<langsyntaxhighlight lang="rust">#![feature(core)]
 
fn sumsqd(mut n: i32) -> i32 {
Line 6,186 ⟶ 6,828:
 
println!("{:?}", happy)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,193 ⟶ 6,835:
 
=={{header|Salmon}}==
<langsyntaxhighlight Salmonlang="salmon">variable happy_count := 0;
outer:
iterate(x; [1...+oo])
Line 6,221 ⟶ 6,863:
now := new;
};
};</langsyntaxhighlight>
This Salmon program produces the following output:
<pre>1 is happy.
Line 6,233 ⟶ 6,875:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">scala> def isHappy(n: Int) = {
| new Iterator[Int] {
| val seen = scala.collection.mutable.Set[Int]()
Line 6,257 ⟶ 6,899:
28
31
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (number->list num)
(do ((num num (quotient num 10))
(lst '() (cons (remainder num 10) lst)))
Line 6,276 ⟶ 6,918:
(cond ((= more 0) (newline))
((happy? n) (display " ") (display n) (loop (+ n 1) (- more 1)))
(else (loop (+ n 1) more))))</langsyntaxhighlight>
The output is:
<pre>happy numbers: 1 7 10 13 19 23 28 31</pre>
Line 6,288 ⟶ 6,930:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: cacheType is hash [integer] boolean;
Line 6,329 ⟶ 6,971:
end if;
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 6,347 ⟶ 6,989:
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang="sequencel">import <Utilities/Math.sl>;
import <Utilities/Conversion.sl>;
 
Line 6,373 ⟶ 7,015:
true when n = 1
else
isHappyHelper(newN, cache ++ [n]);</langsyntaxhighlight>
 
{{out}}
Line 6,382 ⟶ 7,024:
 
=={{header|SETL}}==
<langsyntaxhighlight SETLlang="setl">proc is_happy(n);
s := [n];
while n > 1 loop
Line 6,391 ⟶ 7,033:
end while;
return true;
end proc;</langsyntaxhighlight>
<langsyntaxhighlight SETLlang="setl">happy := [];
n := 1;
until #happy = 8 loop
Line 6,399 ⟶ 7,041:
end loop;
 
print(happy);</langsyntaxhighlight>
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Alternative version:
<langsyntaxhighlight SETLlang="setl">print([n : n in [1..100] | is_happy(n)](1..8));</langsyntaxhighlight>
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func happy(n) is cached {
static seen = Hash()
 
Line 6,418 ⟶ 7,060:
}
 
say happy.first(8)</langsyntaxhighlight>
 
{{out}}
Line 6,429 ⟶ 7,071:
{{trans|Python}}
In addition to the "Python's cache mechanism", the use of a Bag assures that found e.g. the happy 190, we already have in cache also the happy 910 and 109, and so on.
<langsyntaxhighlight lang="smalltalk">Object subclass: HappyNumber [
|cache negativeCache|
HappyNumber class >> new [ |me|
Line 6,491 ⟶ 7,133:
]
]
].</langsyntaxhighlight>
<langsyntaxhighlight lang="smalltalk">|happy|
happy := HappyNumber new.
 
Line 6,498 ⟶ 7,140:
(happy isHappy: i)
ifTrue: [ i displayNl ]
].</langsyntaxhighlight>
Output:
1
Line 6,511 ⟶ 7,153:
an alternative version is:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|next isHappy happyNumbers|
 
next :=
Line 6,535 ⟶ 7,177:
try := try + 1
].
happyNumbers printCR</langsyntaxhighlight>
Output:
OrderedCollection(1 7 10 13 19 23 28 31)
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func isHappyNumber(var n:Int) -> Bool {
var cycle = [Int]()
Line 6,564 ⟶ 7,206:
}
count++
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,578 ⟶ 7,220:
=={{header|Tcl}}==
using code from [[Sum of squares#Tcl]]
<langsyntaxhighlight lang="tcl">proc is_happy n {
set seen [list]
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
Line 6,593 ⟶ 7,235:
incr n
}
puts "the first 8 happy numbers are: [list $happy]"</langsyntaxhighlight>
<pre>the first 8 happy numbers are: {1 7 10 13 19 23 28 31}</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
SECTION check
IF (n!=1) THEN
Line 6,632 ⟶ 7,274:
DO check
ENDLOOP
ENDLOOP</langsyntaxhighlight>
Output:
<pre>
Line 6,645 ⟶ 7,287:
</pre>
 
=={{header|uBasic/4tHUiua}}==
{{works with|Uiua|0.10.0-dev.1}}
<lang>
<syntaxhighlight lang="Uiua">
' ************************
HC ← /+ⁿ2≡⋕°⋕ # Happiness calc = sum of squares of digits
' MAIN
IH ← |2 memo⟨IH ⊙⊂.|=1⟩∊,, HC # Apply HC until seen value recurs
' ************************
Happy ← ⟨0◌|∘⟩IH : [1] . # Pre-load `seen` with 1. Return start number or 0
 
# Brute force approach isn't too bad with memoisation even for high bounds.
PROC _PRINT_HAPPY(20)
↙8⊚>0≡Happy⇡10000
END
 
# But iterative approach is still much faster
' ************************
NH ← |1 ⟨NH|∘⟩≠0Happy.+1 # Find next Happy number
' END MAIN
⇌[⍥(NH.) 7 1]
' ************************
</syntaxhighlight>
 
' ************************
' SUBS & FUNCTIONS
' ************************
 
' --------------------
_is_happy PARAM(1)
' --------------------
LOCAL (5)
f@ = 100
c@ = a@
b@ = 0
 
DO WHILE b@ < f@
e@ = 0
 
DO WHILE c@
d@ = c@ % 10
c@ = c@ / 10
e@ = e@ + (d@ * d@)
LOOP
 
UNTIL e@ = 1
c@ = e@
b@ = b@ + 1
LOOP
 
RETURN(b@ < f@)
 
' --------------------
_PRINT_HAPPY PARAM(1)
' --------------------
LOCAL (2)
b@ = 1
c@ = 0
 
DO
 
IF FUNC (_is_happy(b@)) THEN
c@ = c@ + 1
PRINT b@
ENDIF
 
b@ = b@ + 1
UNTIL c@ + 1 > a@
LOOP
 
RETURN
 
' ************************
' END SUBS & FUNCTIONS
' ************************
</lang>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
<lang bash>#!/bin/bash
{{works with|Z Shell}}
function sum_of_square_digits
<syntaxhighlight lang="bash">function sum_of_square_digits {
{
localtypeset -i n="$1" sum=0 d
while (( n )); do
local -i(( d=n%10, sum+=d*d, n=n/10 ))
let sum+=d*d
let n=n/10
done
echoprintf '%d\n' "$sum"
}
 
function is_happy? {
typeset -i n=$1
{
localtypeset -ia nseen="$1"()
local seen=()
while (( n != 1 )); do
if [[ -n "${seen[$n]}" ]]; then
return 1
fi
seen[$n]=1
let(( n="$(sum_of_square_digits "$n")" ))
done
return 0
}
 
function first_n_happy {
typeset -i count=$1 n
{
localfor -i(( 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
return 0
}
 
first_n_happy 8</langsyntaxhighlight>
Output:<pre>1
7
10
13
19
23
28
31</pre>
 
=={{header|Ursala}}==
Line 6,766 ⟶ 7,344:
and first(p) defines a function mapping a number n to the first n
positive naturals having property p.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 6,775 ⟶ 7,353:
#cast %nL
 
main = (first happy) 8</langsyntaxhighlight>
output:
<pre><1,7,10,13,19,23,28,31></pre>
Line 6,781 ⟶ 7,359:
=={{header|Vala}}==
{{libheader|Gee}}
<langsyntaxhighlight lang="vala">using Gee;
 
/* function to sum the square of the digits */
Line 6,826 ⟶ 7,404:
stdout.printf("%d ", num);
stdout.printf("\n");
} // end main</langsyntaxhighlight>
The output is:
<pre>
Line 6,832 ⟶ 7,410:
</pre>
 
=={{header|VBAV (Vlang)}}==
 
<lang vb>
Option Explicit
 
Sub Test_Happy()
Dim i&, Cpt&
 
For i = 1 To 100
If Is_Happy_Number(i) Then
Debug.Print "Is Happy : " & i
Cpt = Cpt + 1
If Cpt = 8 Then Exit For
End If
Next
End Sub
 
Public Function Is_Happy_Number(ByVal N As Long) As Boolean
Dim i&, Number$, Cpt&
Is_Happy_Number = False 'default value
Do
Cpt = Cpt + 1 'Count Loops
Number = CStr(N) 'conversion Long To String to be able to use Len() function
N = 0
For i = 1 To Len(Number)
N = N + CInt(Mid(Number, i, 1)) ^ 2
Next i
'If Not N = 1 after 50 Loop ==> Number Is Not Happy
If Cpt = 50 Then Exit Function
Loop Until N = 1
Is_Happy_Number = True
End Function
</lang>
{{Out}}
<pre>Is Happy : 1
Is Happy : 7
Is Happy : 10
Is Happy : 13
Is Happy : 19
Is Happy : 23
Is Happy : 28
Is Happy : 31</pre>
 
=={{header|VBScript}}==
<lang vb>
count = 0
firsteigth=""
For i = 1 To 100
If IsHappy(CInt(i)) Then
firsteight = firsteight & i & ","
count = count + 1
End If
If count = 8 Then
Exit For
End If
Next
WScript.Echo firsteight
 
Function IsHappy(n)
IsHappy = False
m = 0
Do Until m = 60
sum = 0
For j = 1 To Len(n)
sum = sum + (Mid(n,j,1))^2
Next
If sum = 1 Then
IsHappy = True
Exit Do
Else
n = sum
m = m + 1
End If
Loop
End Function
</lang>
 
{{Out}}
<pre>1,7,10,13,19,23,28,31,</pre>
 
=={{header|Visual Basic .NET}}==
This version uses Linq to carry out the calculations.
<lang vbnet>Module HappyNumbers
Sub Main()
Dim n As Integer = 1
Dim found As Integer = 0
 
Do Until found = 8
If IsHappy(n) Then
found += 1
Console.WriteLine("{0}: {1}", found, n)
End If
n += 1
Loop
 
Console.ReadLine()
End Sub
 
Private Function IsHappy(ByVal n As Integer)
Dim cache As New List(Of Long)()
 
Do Until n = 1
cache.Add(n)
n = Aggregate c In n.ToString() _
Into Total = Sum(Int32.Parse(c) ^ 2)
If cache.Contains(n) Then Return False
Loop
 
Return True
End Function
End Module</lang>
The output is:
<pre>1: 1
2: 7
3: 10
4: 13
5: 19
6: 23
7: 28
8: 31</pre>
===Cacheless version===
{{trans|C#}}
Curiously, this runs in about two thirds of the time of the cacheless C# version on Tio.run.
<lang vbnet>Module Module1
 
Dim sq As Integer() = {1, 4, 9, 16, 25, 36, 49, 64, 81}
 
Function isOne(x As Integer) As Boolean
While True
If x = 89 Then Return False
Dim t As Integer, s As Integer = 0
Do
t = (x Mod 10) - 1 : If t >= 0 Then s += sq(t)
x \= 10
Loop While x > 0
If s = 1 Then Return True
x = s
End While
Return False
End Function
 
Sub Main(ByVal args As String())
Const Max As Integer = 10_000_000
Dim st As DateTime = DateTime.Now
Console.Write("---Happy Numbers---" & vbLf & "The first 8:")
Dim i As Integer = 1, c As Integer = 0
While c < 8
If isOne(i) Then Console.Write("{0} {1}", If(c = 0, "", ","), i, c) : c += 1
i += 1
End While
Dim m As Integer = 10
While m <= Max
Console.Write(vbLf & "The {0:n0}th: ", m)
While c < m
If isOne(i) Then c += 1
i += 1
End While
Console.Write("{0:n0}", i - 1)
m = m * 10
End While
Console.WriteLine(vbLf & "Computation time {0} seconds.", (DateTime.Now - st).TotalSeconds)
End Sub
End Module</lang>
{{out}}
<pre>---Happy Numbers---
The first 8: 1, 7, 10, 13, 19, 23, 28, 31
The 10th: 44
The 100th: 694
The 1,000th: 6,899
The 10,000th: 67,169
The 100,000th: 692,961
The 1,000,000th: 7,105,849
The 10,000,000th: 71,313,350
Computation time 19.235551 seconds.</pre>
 
=={{header|Vlang}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn happy(h int) bool {
mut m := map[int]bool{}
mut n := h
Line 7,034 ⟶ 7,437:
}
println('')
}</langsyntaxhighlight>
{{out}}
<pre>
Line 7,042 ⟶ 7,445:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">var happy = Fn.new { |n|
var m = {}
while (n > 1) {
Line 7,067 ⟶ 7,470:
n = n + 1
}
System.print()</langsyntaxhighlight>
 
{{out}}
Line 7,081 ⟶ 7,484:
numbers.
 
<langsyntaxhighlight XPL0lang="xpl0">int List(810); \list of numbers in a cycle
int Inx; \index for List
include c:\cxpl\codes;
Line 7,125 ⟶ 7,528:
N0:= N0+1; \next starting number
until C=8; \done when 8 happy numbers have been found
]</langsyntaxhighlight>
 
Output:
Line 7,140 ⟶ 7,543:
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
Line 7,177 ⟶ 7,580:
return s;
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 7,185 ⟶ 7,588:
Here is a function that generates a continuous stream of happy numbers. Given that there are lots of happy numbers, caching them doesn't seem like a good idea memory wise. Instead, a num of squared digits == 4 is used as a proxy for a cycle (see the Wikipedia article, there are several number that will work).
{{trans|Icon and Unicon}}
<langsyntaxhighlight lang="zkl">fcn happyNumbers{ // continously spew happy numbers
foreach N in ([1..]){
n:=N; while(1){
Line 7,193 ⟶ 7,596:
}
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">h:=Utils.Generator(happyNumbers);
h.walk(8).println();</langsyntaxhighlight>
{{out}}
<pre>L(1,7,10,13,19,23,28,31)</pre>
Get the one million-th happy number. Nobody would call this quick.
<langsyntaxhighlight lang="zkl">Utils.Generator(happyNumbers).drop(0d1_000_000-1).next().println();</langsyntaxhighlight>
{{out}}<pre>7105849</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|Run_BASIC}}
<lang zxbasic>10 FOR i=1 TO 100
20 GO SUB 1000
30 IF isHappy=1 THEN PRINT i;" is a happy number"
40 NEXT i
50 STOP
1000 REM Is Happy?
1010 LET isHappy=0: LET count=0: LET num=i
1020 IF count=50 OR isHappy=1 THEN RETURN
1030 LET n$=STR$ (num)
1040 LET count=count+1
1050 LET isHappy=0
1060 FOR j=1 TO LEN n$
1070 LET isHappy=isHappy+VAL n$(j)^2
1080 NEXT j
1090 LET num=isHappy
1100 GO TO 1020</lang>
66

edits