Happy numbers: Difference between revisions
m
→{{header|Uiua}}: slightly nicer algorithm
(Happy numbers in BASIC256) |
m (→{{header|Uiua}}: slightly nicer algorithm) |
||
(39 intermediate revisions by 20 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}}
<
Set[Int] past
L n != 1
Line 33 ⟶ 36:
R 1B
print((0.<500).filter(x -> happy(x))[0.<8])</
{{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.
<
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,'$'</
{{out}}
Line 143 ⟶ 146:
=={{header|8th}}==
<
: until! "not while!" eval i;
Line 173 ⟶ 176:
;with
;with
</syntaxhighlight>
{{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}}==
<
(defun sum-of-digit-squares (n)
Line 205 ⟶ 242:
(defun first-happy-nums (n)
(first-happy-nums-r n 1))</
Output:
<pre>(1 7 10 13 19 23 28 31)</pre>
=={{header|Action!}}==
<
BYTE sum,d
Line 260 ⟶ 297:
x==+1
OD
RETURN</
{{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}}==
<
{
var sum:uint = 0;
Line 316 ⟶ 353:
}
}
printHappy();</
Sample output:
<pre>
Line 330 ⟶ 367:
=={{header|Ada}}==
<
with Ada.Containers.Ordered_Sets;
Line 370 ⟶ 407:
end if;
end loop;
end Test_Happy_Digits;</
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}}
<
PROC next = (INT in n)INT: (
Line 404 ⟶ 441:
print((i, new line))
FI
OD</
Output:
<pre>
Line 418 ⟶ 455:
=={{header|ALGOL-M}}==
<
integer function mod(a,b);
integer a,b;
Line 455 ⟶ 492:
i := i + 1;
end;
end</
{{out}}
<pre> 1
Line 467 ⟶ 504:
=={{header|ALGOL W}}==
<
% when repeatedly applied %
% returns true if n is happy, false otherwise %
logical procedure isHappy ( integer value n ) ;
begin
% in base ten, numbers either reach 1 or loop around a sequence %
% containing 4 (see the Wikipedia article) %
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 );
end
n := n + 1
end
end
end.
</syntaxhighlight>
{{out}}
<pre>
</pre>
Line 529 ⟶ 550:
===Tradfn===
<
[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
∇</
<pre>
HappyNumbers 100 8
Line 555 ⟶ 576:
===Dfn===
<syntaxhighlight lang="apl">
HappyNumbers←{ ⍝ return the first ⍵ Happy Numbers
⍺←⍬ ⍝ initial list
Line 570 ⟶ 591:
HappyNumbers 8
1 7 10 13 19 23 28 31
</syntaxhighlight>
=={{header|AppleScript}}==
===Iteration===
<
set howManyHappyNumbers to 8
set happyNumberList to {}
Line 606 ⟶ 627:
end repeat
return (numberToCheck = 1)
end isHappy</
<pre>
Result: (*1, 7, 10, 13, 19, 23, 28, 31*)
Line 614 ⟶ 635:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<
-- isHappy :: Int -> Bool
Line 740 ⟶ 761:
end tell
return v
end |until|</
{{Out}}
<
=={{header|Arturo}}==
Line 748 ⟶ 769:
{{trans|Nim}}
<
happy?: function [x][
n: x
Line 768 ⟶ 789:
loop 0..31 'x [
if happy? x -> print x
]</
{{out}}
Line 782 ⟶ 803:
=={{header|AutoHotkey}}==
<
If isHappy(A_Index) {
out .= (out="" ? "" : ",") . A_Index
Line 802 ⟶ 823:
Return false
Else Return isHappy(sum, list)
}</
<pre>
The first 8 happy numbers are: 1,7,10,13,19,23,28,31
</pre>
===Alternative version===
<
if (Happy(A_Index)) {
Out .= A_Index A_Space
Line 824 ⟶ 845:
n := t, t := 0
}
}</
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|AutoIt}}==
<
$c = 0
$k = 0
Line 851 ⟶ 872:
EndIf
WEnd
</syntaxhighlight>
<pre>
Line 867 ⟶ 888:
===Alternative version===
<
$c = 0
$k = 0
Line 892 ⟶ 913:
$a.Clear
WEnd
</syntaxhighlight>
<pre>
Saves all numbers in a list, duplicate entry indicates a loop.
Line 907 ⟶ 928:
=={{header|AWK}}==
<
{
if ( n in happy ) return 1;
Line 947 ⟶ 968:
}
}
}</
Result:
<pre>1
Line 962 ⟶ 983:
Alternately, for legibility one might write:
<
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
Line 989 ⟶ 1,010:
}
return tot
}</
=={{header|
==={{header|Applesoft BASIC}}===
<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,016 ⟶ 1,051:
num = isHappy
end while
end function</
==={{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
<
setlocal enableDelayedExpansion
::Define a list with 10 terms as a convenience for defining a loop
Line 1,100 ⟶ 1,661:
)
set /a n=sum
)</
Sample usage and output
<pre>
Line 1,157 ⟶ 1,718:
ERROR: Maximum integer value reached
</pre>
=={{header|BCPL}}==
<
let sumdigitsq(n) =
Line 1,216 ⟶ 1,744:
$)
wrch('*N')
$)</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Bori}}==
<
{
ints cache;
Line 1,256 ⟶ 1,784:
}
puts("First 8 happy numbers : " + str.newline + happynums);
}</
Output:
<pre>First 8 happy numbers :
Line 1,262 ⟶ 1,790:
=={{header|BQN}}==
<
Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢
8↑Happy¨⊸/↕50</
{{out}}
<pre>⟨ 1 7 10 13 19 23 28 31 ⟩</pre>
=={{header|Brat}}==
<
happiness = set.new 1
Line 1,297 ⟶ 1,825:
p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"</
Output:
<pre>First eight happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]
Line 1,305 ⟶ 1,833:
=={{header|C}}==
Recursively look up if digit square sum is happy.
<
#define CACHE 256
Line 1,337 ⟶ 1,865:
return 0;
}</
output<pre>1 7 10 13 19 23 28 31
The 1000000th happy number: 7105849</pre>
Without caching, using cycle detection:
<
int dsum(int n)
Line 1,371 ⟶ 1,899:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,422 ⟶ 1,950:
}
}
}</
<pre>
First 8 happy numbers : 1,7,10,13,19,23,28,31
Line 1,429 ⟶ 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).<
using System.Collections.Generic;
class Program
Line 1,462 ⟶ 1,990:
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}</
{{out}}
<pre>---Happy Numbers---
Line 1,477 ⟶ 2,005:
=={{header|C++}}==
{{trans|Python}}
<
#include <set>
Line 1,512 ⟶ 2,040:
std::cout << i << std::endl;
return 0;
}</
Output:
<pre>1
Line 1,526 ⟶ 2,054:
49</pre>
Alternative version without caching:
<
{
unsigned int result = 0;
Line 1,566 ⟶ 2,094:
}
std::cout << std::endl;
}</
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 1,572 ⟶ 2,100:
=={{header|Clojure}}==
<
(loop [n n, seen #{}]
(cond
Line 1,586 ⟶ 2,114:
(def happy-numbers (filter happy? (iterate inc 1)))
(println (take 8 happy-numbers))</
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
===Alternate Version (with caching)===
<
(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})})
Line 1,623 ⟶ 2,151:
(filter #(= :happy (happy-algo %)))))
(println (take 8 happy-numbers))</
Same output.
=={{header|CLU}}==
<
sum_sq: int := 0
while n > 0 do
Line 1,662 ⟶ 2,190:
stream$putl(po, int$unparse(i))
end
end start_up </
{{out}}
<pre>1
Line 1,672 ⟶ 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}}==
<
seen = {}
while true
Line 1,695 ⟶ 2,290:
console.log i
cnt += 1
i += 1</
output
<pre>
Line 1,710 ⟶ 2,305:
=={{header|Common Lisp}}==
<
(* n n))
Line 1,731 ⟶ 2,326:
(print (happys))
</syntaxhighlight>
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
=={{header|Cowgol}}==
<
sub sumDigitSquare(n: uint8): (s: uint8) is
Line 1,773 ⟶ 2,368:
end if;
n := n + 1;
end loop;</
{{out}}
Line 1,788 ⟶ 2,383:
=={{header|Crystal}}==
{{trans|Ruby}}
<
past = [] of Int32 | Int64
until n == 1
Line 1,801 ⟶ 2,396:
until count == 8; (puts i; count += 1) if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</
{{out}}
<pre>
Line 1,827 ⟶ 2,422:
=={{header|D}}==
<
int[int] past;
Line 1,849 ⟶ 2,444:
int.max.iota.filter!isHappy.take(8).writeln;
}</
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
===Alternative Version===
<
bool isHappy(int n) pure nothrow {
Line 1,871 ⟶ 2,466:
void main() {
int.max.iota.filter!isHappy.take(8).writeln;
}</
Same output.
=={{header|Dart}}==
<
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
Line 1,909 ⟶ 2,504:
i++;
}
}</
=={{header|dc}}==
<
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx</
Output:
<pre>1
Line 1,927 ⟶ 2,522:
=={{header|DCL}}==
<
$ found = 0
$ i = 1
Line 1,976 ⟶ 2,571:
$ goto loop1
$ done:
$ show symbol found*</
{{out}}
<pre> FOUND = 8 Hex = 00000008 Octal = 00000000010
Line 1,991 ⟶ 2,586:
{{libheader| Boost.Int}}
Adaptation of [[#Pascal]]. The lib '''Boost.Int''' can be found here [https://github.com/MaiconSoft/DelphiBoostLib]
<syntaxhighlight lang="delphi">
program Happy_numbers;
Line 2,055 ⟶ 2,650:
writeln;
readln;
end.</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Draco}}==
<
byte r, d;
r := 0;
Line 2,092 ⟶ 2,687:
n := n + 1
od
corp</
{{out}}
<pre> 1
Line 2,104 ⟶ 2,699:
=={{header|DWScript}}==
<
var
cache : array of Integer;
Line 2,133 ⟶ 2,728:
Dec(n);
end;
end;</
Output:
<pre>1
Line 2,146 ⟶ 2,741:
=={{header|Dyalect}}==
<
var m = []
while n > 1 {
Line 2,172 ⟶ 2,767:
n += 1
}
print()</
{{out}}
Line 2,179 ⟶ 2,774:
=={{header|Déjà Vu}}==
<
0
while over:
Line 2,215 ⟶ 2,810:
++
drop
drop</
{{output}}
<pre>A happy number: 1
Line 2,228 ⟶ 2,823:
=={{header|E}}==
{{output?|E}}
<
var seen := [].asSet()
while (!seen.contains(x)) {
Line 2,247 ⟶ 2,842:
println(x)
if ((count += 1) >= 8) { break }
}</
=={{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">
class
APPLICATION
Line 2,322 ⟶ 2,952:
end
</syntaxhighlight>
=={{header|Elena}}==
{{trans|C#}}
ELENA
<
import system'collections;
import system'routines;
Line 2,338 ⟶ 2,968:
while (num != 1)
{
if (cache.indexOfElement
{
^ false
Line 2,345 ⟶ 2,975:
while (num != 0)
{
int digit := num.mod
sum += (digit*digit);
num /= 10
Line 2,370 ⟶ 3,000:
};
console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}</
{{out}}
<pre>
Line 2,377 ⟶ 3,007:
=={{header|Elixir}}==
<
def task(num) do
Process.put({:happy, 1}, true)
Line 2,403 ⟶ 3,033:
end
IO.inspect Happy.task(8)</
{{out}}
Line 2,411 ⟶ 3,041:
=={{header|Erlang}}==
<
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
Line 2,443 ⟶ 3,073:
main() ->
main(0, []).
</syntaxhighlight>
Command: <
Output: <
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):
<
-export([main/0]).
Line 2,465 ⟶ 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.</
Output:
<pre>[1,7,10,13,19,23,28,31]</pre>
=={{header|Euphoria}}==
<
sequence seen
integer k
Line 2,498 ⟶ 3,128:
end if
n += 1
end while</
Output:
<pre>1
Line 2,512 ⟶ 3,142:
=={{header|F_Sharp|F#}}==
This requires the F# power pack to be referenced and the 2010 beta of F#
<
open Microsoft.FSharp.Collections
Line 2,541 ⟶ 3,171:
|> Seq.truncate 8 // Stop when we've found 8
|> Seq.iter (Printf.printf "%d\n") // Print results
</syntaxhighlight>
Output:
<pre>
Line 2,555 ⟶ 3,185:
=={{header|Factor}}==
<
: squares ( n -- s )
Line 2,575 ⟶ 3,205:
dup happy? [ dup , [ 1 - ] dip ] when 1 +
] while 2drop
] { } make ;</
{{out}}
<
=={{header|FALSE}}==
<
[$m;![$9>][m;!@@+\]#$*+]s: {sum of squares}
[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates}
Line 2,594 ⟶ 3,224:
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%</
{{out}}
Line 2,600 ⟶ 3,230:
=={{header|Fantom}}==
<
{
static Bool isHappy (Int n)
Line 2,635 ⟶ 3,265:
}
}
</syntaxhighlight>
Output:
<pre>
Line 2,649 ⟶ 3,279:
=={{header|FOCAL}}==
<
01.20 D 3;I (K-2)1.5
01.30 S N=N+1
Line 2,667 ⟶ 3,297:
03.30 S S(K)=0
03.40 D 2;S K=R
03.50 I (S(K))3.3</
{{out}}
Line 2,681 ⟶ 3,311:
=={{header|Forth}}==
<
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
Line 2,700 ⟶ 3,330:
loop drop ;
8 happy-numbers \ 1 7 10 13 19 23 28 31</
===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.
<
: next ( n -- n')
0 swap BEGIN dup WHILE 10 /mod >r dup * + r> REPEAT drop ;
Line 2,713 ⟶ 3,343:
BEGIN 1+ dup happy? UNTIL dup . r> 1- >r
REPEAT r> drop drop ;
8 happy-numbers</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Produces the 1 millionth happy number with:
<
>r 0 BEGIN r@ WHILE
BEGIN 1+ dup happy? UNTIL r> 1- >r
REPEAT r> drop ;
1000000 happy-number . \ 7105849</
in about 9 seconds.
=={{header|Fortran}}==
<
implicit none
Line 2,791 ⟶ 3,421:
end function is_happy
end program happy</
Output:
<pre>1
Line 2,801 ⟶ 3,431:
28
31</pre>
=={{header|Frege}}==
Line 2,865 ⟶ 3,437:
{{Works with|Frege|3.21.586-g026e8d7}}
<
import Prelude.Math
Line 2,881 ⟶ 3,453:
f = sum . map (sqr . digitToInteger) . unpacked . show
main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n</
{{out}}
Line 2,888 ⟶ 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}}
'''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]]
[[File:Fōrmulæ - Happy numbers 03.png]]
=={{header|Go}}==
<
import "fmt"
Line 2,927 ⟶ 3,552:
}
fmt.Println()
}</
{{out}}
<pre>
Line 2,934 ⟶ 3,559:
=={{header|Groovy}}==
<
def number = delegate as Long
def cycle = new HashSet<Long>()
Line 2,948 ⟶ 3,573:
if (i.happy) { matches << i }
}
println matches</
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|Harbour}}==
<
LOCAL i := 8, nH := 0
Line 2,985 ⟶ 3,610:
AAdd( aUnhappy, nSum )
RETURN IsHappy( nSum )</
Output:
Line 2,992 ⟶ 3,617:
=={{header|Haskell}}==
<
import Data.Set (member, insert, empty)
Line 3,005 ⟶ 3,630:
main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]</
{{Out}}
<pre>1
Line 3,017 ⟶ 3,642:
We can create a cache for small numbers to greatly speed up the process:
<
happy :: Int -> Bool
Line 3,035 ⟶ 3,660:
main :: IO ()
main = print $ sum $ take 10000 $ filter happy [1 ..]</
{{Out}}
<pre>327604323</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
local n
n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8
Line 3,056 ⟶ 3,681:
if happy(n) then return i
}
end</
Usage and Output:
<pre>
Line 3,065 ⟶ 3,690:
=={{header|J}}==
<
1 7 10 13 19 23 28 31</
This is a repeat while construction
<
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.
<
So for easier reading the solution could be expressed as:
<
sumSqrDigits=: +/@(*:@(,.&.":))
Line 3,078 ⟶ 3,703:
14
8{. (#~ 1 = sumSqrDigits ^: cond ^:_ "0) 1 + i.100
1 7 10 13 19 23 28 31</
=={{header|Java}}==
{{works with|Java|1.5+}}
{{trans|JavaScript}}
<
public class Happy{
public static boolean happy(long number){
Line 3,109 ⟶ 3,734:
}
}
}</
Output:
<pre>1
Line 3,124 ⟶ 3,749:
{{works with|Java|1.8}}
{{trans|Java}}
<
import java.util.Arrays;
Line 3,151 ⟶ 3,776:
return number == 1;
}
}</
Output:
<pre>1
Line 3,166 ⟶ 3,791:
===ES5===
====Iteration====
<
var m, digit ;
var cycle = [] ;
Line 3,191 ⟶ 3,816:
document.write(number + " ") ;
number++ ;
}</
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 3,198 ⟶ 3,823:
====Functional composition====
{{Trans|Haskell}}
<
// isHappy :: Int -> Bool
Line 3,257 ⟶ 3,882:
take(8, filter(isHappy, enumFromTo(1, 50)))
);
})()</
{{Out}}
<
Or, to stop immediately at the 8th member of the series, we can preserve functional composition while using an iteratively implemented '''until()''' function:
<
// isHappy :: Int -> Bool
Line 3,332 ⟶ 3,957:
.xs
);
})();</
{{Out}}
<
=={{header|jq}}==
{{works with|jq|1.4}}
<
def next: tostring | explode | map( (. - 48) | .*.) | add;
def last(g): reduce g as $i (null; $i);
Line 3,352 ⟶ 3,977:
end
end );
1 == last( [.,{}] | loop );</
'''Emit a stream of the first n happy numbers''':
<
def happy(n):
def subtask: # state: [i, found]
Line 3,365 ⟶ 3,990:
[0,0] | subtask;
happy($n|tonumber)</
{{out}}
<
1
7
Line 3,376 ⟶ 4,001:
28
31
</syntaxhighlight>
=={{header|Julia}}==
<
function happy(x)
happy_ints =
int_try = 1
while length(happy_ints) < x
n = int_try
past =
while n != 1
push!(past, n)
end
n == 1 && push!(happy_ints,int_try)
int_try += 1
end
return happy_ints
end</
Output
<pre> julia> happy(8)
Line 3,407 ⟶ 4,033:
31</pre>
A recursive version:
<
function ishappy(x, mem = Int[])
x == 1 ? true :
x in mem ? false :
ishappy(sumhappy(x), [mem ; x])
end
nexthappy
happy(n) = accumulate((a, b) -> nexthappy(a), 1:n)
</syntaxhighlight>
{{Out}}
<pre>julia> show(happy(8))
Line 3,426 ⟶ 4,051:
Faster with use of cache
{{trans|C}}
<
buf = zeros(Int, CACHE)
buf[
function happy(n)
if n < CACHE
Line 3,435 ⟶ 4,060:
buf[n] = 2
end
nn = n
while nn != 0
nn, x = divrem(nn
end
x = happy(
n < CACHE && (buf[n] = 2 - x)
return x
end
function main()
i, counter = 1
while counter > 0
if happy(i)
counter -= 1
end
i += 1
end
return i - 1
end
</syntaxhighlight>
=={{header|K}}==
<
hpy 1+!100
Line 3,464 ⟶ 4,090:
8#hpy 1+!100
1 7 10 13 19 23 28 31</
Another implementation which is easy to follow is given below:
<syntaxhighlight lang="k">
/ happynum.k
Line 3,477 ⟶ 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>
The output of a session with this implementation is given below:
Line 3,492 ⟶ 4,118:
=={{header|Kotlin}}==
{{trans|C#}}
<
fun isHappy(n: Int): Boolean {
Line 3,521 ⟶ 4,147:
}
println("First 8 happy numbers : " + happyNums.joinToString(", "))
}</
{{out}}
Line 3,527 ⟶ 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}}==
<
define isHappy(n::integer) => {
Line 3,543 ⟶ 4,203:
where isHappy(#x)
take 8
select #x</
Output:
<
=={{header|Logo}}==
<
output (apply "sum (map [[d] d*d] ` :number))
end
Line 3,633 ⟶ 4,232:
print n_happy 8
bye</
Output:
Line 3,641 ⟶ 4,240:
{{works with|lci 0.10.3}}
<
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
Line 3,723 ⟶ 4,322:
OIC
IM OUTTA YR LOOP
KTHXBYE</
Output:<pre>1
Line 3,735 ⟶ 4,334:
=={{header|Lua}}==
<
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
Line 3,749 ⟶ 4,348:
repeat
i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8</
Output:
<pre>1
Line 3,766 ⟶ 4,365:
<syntaxhighlight lang="m2000 interpreter">
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
Line 3,799 ⟶ 4,398:
PrintHappy=factoryHappy()
Call PrintHappy()
</syntaxhighlight>
{{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,813 ⟶ 4,482:
=={{header|MAD}}==
<
BOOLEAN CYCLE
DIMENSION CYCLE(200)
Line 3,841 ⟶ 4,510:
END OF PROGRAM
</syntaxhighlight>
{{out}}
Line 3,856 ⟶ 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.)
<
local s := 0;
local m := n;
Line 3,863 ⟶ 4,532:
end do;
s
end proc:</
(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">
> SumSqDigits( 1234567890987654321 );
570
</syntaxhighlight>
We can check this by computing it another way (more directly).
<syntaxhighlight lang="maple">
> n := 1234567890987654321:
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
570
</syntaxhighlight>
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).
<
if n = 1 then
true
Line 3,890 ⟶ 4,559:
evalb( s = 1 )
end if
end proc:</
We can use this to determine the number of happy (H) and sad (S) numbers up to one million as follows.
<syntaxhighlight lang="maple">
> H, S := selectremove( Happy?, [seq]( 1 .. N ) ):
> nops( H ), nops( S );
143071, 856929
</syntaxhighlight>
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.
<
local count := 0;
local T := table();
Line 3,908 ⟶ 4,577:
end do;
{seq}( T[ i ], i = 1 .. count )
end proc:</
With input equal to 8, we get
<syntaxhighlight lang="maple">
> FindHappiness( 8 );
{1, 7, 10, 13, 19, 23, 28, 31}
</syntaxhighlight>
For completeness, here is an implementation of the cycle detection algorithm for recognizing happy numbers. It is much slower, however.
<
local a, b;
a, b := n, SumSqDigits( n );
Line 3,923 ⟶ 4,592:
end do;
evalb( a = 1 )
end proc:</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Custom function HappyQ:
<
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1</
Examples for a specific number:
<
HappyQ[137]</
gives back:
<syntaxhighlight lang="mathematica">True
False</
Example finding the first 8:
<
n = 1;
i = 0;
Line 3,948 ⟶ 4,617:
]
]
happynumbers</
gives back:
<
=={{header|MATLAB}}==
Recursive version:
<
nHappy = 0;
k = 1;
Line 3,975 ⟶ 4,644:
hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]);
end
end</
{{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">
fn isHappyNumber n =
(
Line 4,007 ⟶ 4,709:
)
</syntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
1
7
Line 4,018 ⟶ 4,720:
28
31
</syntaxhighlight>
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 4,060 ⟶ 4,762:
:- func sqr(int) = int.
sqr(X) = X * X.</
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 4,066 ⟶ 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.
<
while true
if x == 89 then return false
Line 4,085 ⟶ 4,787:
i = i + 1
end while
print "First 8 happy numbers: " + found</
{{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}}===
<
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,126 ⟶ 4,861:
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
</syntaxhighlight>
Output:
<pre>1 is happy
Line 4,140 ⟶ 4,875:
=={{header|Modula-2}}==
<
FROM InOut IMPORT WriteCard, WriteLn;
Line 4,183 ⟶ 4,918:
INC(num);
END;
END HappyNumbers.</
{{out}}
<pre> 1
Line 4,195 ⟶ 4,930:
=={{header|MUMPS}}==
<
;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,218 ⟶ 4,953:
FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
KILL I
QUIT</
Output:<pre>
USER>D HAPPY^ROSETTA(8)
Line 4,240 ⟶ 4,975:
=={{header|NetRexx}}==
{{trans|REXX}}
<
limit = arg[0] /*get argument for LIMIT. */
say limit
Line 4,267 ⟶ 5,002:
q=sum /*now, lets try the Q sum. */
end
end</
;Output
<pre>
Line 4,385 ⟶ 5,120:
=={{header|Nim}}==
{{trans|Python}}
<
proc happy(n: int): bool =
Line 4,404 ⟶ 5,139:
for x in 0..31:
if happy(x):
echo x</
Output:
<pre>1
Line 4,416 ⟶ 5,151:
=={{header|Objeck}}==
<
use Structure;
Line 4,462 ⟶ 5,197:
}
}
}</
output:
<pre>First 8 happy numbers: 1,7,10,13,19,23,28,31,</pre>
Line 4,468 ⟶ 5,203:
=={{header|OCaml}}==
Using [[wp:Cycle detection|Floyd's cycle-finding algorithm]].
<
let step =
Line 4,492 ⟶ 5,227:
List.iter print_endline (
List.rev_map string_of_num (first 8)) ;;</
Output:
<pre>$ ocaml nums.cma happy_numbers.ml
Line 4,506 ⟶ 5,241:
=={{header|Oforth}}==
<
| cycle |
ListBuffer new ->cycle
Line 4,521 ⟶ 5,256:
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;</
Output:
Line 4,527 ⟶ 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">
count = 0
say "First 8 happy numbers are:"
Line 4,559 ⟶ 5,328:
number = next
end
</syntaxhighlight>
<pre>
First 8 happy numbers are:
Line 4,573 ⟶ 5,342:
=={{header|Oz}}==
<
import
System
Line 4,616 ⟶ 5,385:
in
{System.show {List.take HappyNumbers 8}}
end</
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Line 4,623 ⟶ 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.
<
isHappy(n)={
if(n<262,
Line 4,632 ⟶ 5,401:
)
};
select(isHappy, vector(31,i,i))</
Output:
<pre>%1 = [1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|Pascal}}==
<
uses
Line 4,697 ⟶ 5,466:
end;
writeln;
end.</
Output:
<pre>:> ./HappyNumbers
Line 4,708 ⟶ 5,477:
Extended to 10e18
Tested with Free Pascal 3.0.4
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,957 ⟶ 5,726:
writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0));
end.
</syntaxhighlight>
;output:
<pre>
Line 5,009 ⟶ 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.
<
sub ishappy {
Line 5,020 ⟶ 5,789:
my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n";</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,026 ⟶ 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}}
<
sub is_happy {
my ($n) = @_;
Line 5,038 ⟶ 5,807:
my $n;
is_happy( ++$n ) and print "$n " or redo for 1..8;</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,044 ⟶ 5,813:
=={{header|Phix}}==
Copy of [[Happy_numbers#Euphoria|Euphoria]] tweaked to give a one-line output
<!--<
<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,071 ⟶ 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>
<!--</
{{out}}
<pre>
Line 5,079 ⟶ 5,848:
=={{header|PHP}}==
{{trans|D}}
<
while (1) {
$total = 0;
Line 5,102 ⟶ 5,871:
}
$i++;
}</
<pre>1 7 10 13 19 23 28 31 </pre>
=={{header|Picat}}==
<
println(happy_len(8)).
Line 5,130 ⟶ 5,899:
end,
N := N + 1
end.</
{{out}}
Line 5,136 ⟶ 5,905:
=={{header|PicoLisp}}==
<
(let Seen NIL
(loop
Line 5,148 ⟶ 5,917:
(do 8
(until (happy? (inc 'H)))
(printsp H) ) )</
Output:
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|PILOT}}==
<
:n=0
:i=0
Line 5,189 ⟶ 5,958:
:x=y
J (x):*digit
E :</
{{out}}
<pre>1
Line 5,201 ⟶ 5,970:
=={{header|PL/I}}==
<
declare (i, j, n, m, nh initial (0) ) fixed binary (31);
Line 5,225 ⟶ 5,994:
end;
end test;
</syntaxhighlight>
OUTPUT:
<pre>
Line 5,239 ⟶ 6,008:
=={{header|PL/M}}==
<
/* FIND SUM OF SQUARE OF DIGITS OF NUMBER */
Line 5,309 ⟶ 6,078:
CALL BDOS(0,0);
EOF</
{{out}}
<pre>1
Line 5,321 ⟶ 6,090:
=={{header|Potion}}==
<
isHappy = (n) :
Line 5,340 ⟶ 6,109:
if (isHappy(i)): firstEight append(i).
.
firstEight string print</
=={{header|PowerShell}}==
<
$a=@()
for($i=2;$a.count -lt $n;$i++) {
Line 5,362 ⟶ 6,131:
}
$a -join ','
}</
Output :
<
7,10,13,19,23,28,31,32</
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<
% creation of the list
length(L, Nb),
Line 5,415 ⟶ 6,184:
square(N, SN) :-
SN is N * N.</
Output :
<
L = [1,7,10,13,19,23,28,31].</
=={{header|Python}}==
===Procedural===
<
past = set()
while n != 1:
Line 5,477 ⟶ 6,201:
>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31]</
===Composition of pure functions===
Drawing 8 terms from a non finite stream, rather than assuming prior knowledge of the finite sample size required:
<
from itertools import islice
Line 5,560 ⟶ 6,284:
if __name__ == '__main__':
main()</
{{Out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 5,566 ⟶ 6,290:
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">
[ 0 swap
[ 10 /mod 2 **
Line 5,588 ⟶ 6,312:
drop nip ] is happies ( n --> [ )
8 happies echo</
{{Out}}
Line 5,595 ⟶ 6,319:
=={{header|R}}==
<
{
stopifnot(is.numeric(n) && length(n)==1)
Line 5,623 ⟶ 6,347:
}
happy
}</
Example usage
<syntaxhighlight lang
[1] FALSE
attr(,"cycle")
[1] 4 16 37 58 89 145 42 20
<
which(apply(rbind(1:50), 2, is.happy))</
1 7 10 13 19 23 28 31 32 44 49
<
happies <- c()
i <- 1L
Line 5,640 ⟶ 6,364:
i <- i + 1L
}
happies</
1 7 10 13 19 23 28 31
=={{header|Racket}}==
<
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
Line 5,665 ⟶ 6,389:
x))
(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)</
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-13}}
<syntaxhighlight lang="raku"
loop {
state %seen;
Line 5,679 ⟶ 6,403:
}
say join ' ', grep(&happy, 1 .. *)[^8];</
{{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"
my %stopper = 1 => 1;
my $n = $number;
Line 5,692 ⟶ 6,416:
}
say ~@happy[^8];</
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"
$n == 1 ?? True !!
$n < 7 ?? False !!
Line 5,702 ⟶ 6,426:
}
say (grep Happy, 1 .. *)[^8];</
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">
function happy(x)
set y = x
Line 5,740 ⟶ 6,501:
set i = i + 1
end while
</syntaxhighlight>
<pre>
Line 5,754 ⟶ 6,515:
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program computes and displays a specified range of happy numbers. */
Call time 'R'
linesize=80
Parse Arg low high /* obtain range of happy numbers */
If low='?' Then Call help
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:
Parse Arg list
Do While list<>''
Parse Var list s list
unhappy.s=1
End
Return
out:
Parse Arg hn
If length(ol hn)>linesize Then Do /* if it does not fit */
End
Else /* otherwise
ol=ol hn /* append is to the output line */
Return
help:
Say 'rexx hno low high show happy numbers from index low to high'
Exit
</syntaxhighlight>
{{out}}
<pre>
K:\_B\HN>rexx hno ?
rexx hno n compute and show the first n happy numbers
rexx hno low high show happy numbers from index low to
K:\_B\HN>rexx hno 8
1 7 10 13 19 23 28 31
K:\_B\HN>rexx hno 1000 1003
6899 6904 6917 6923
</pre>
=={{header|Ring}}==
<
found = 0
Line 5,968 ⟶ 6,632:
End
Return True
</syntaxhighlight>
{{out}}
<pre>
Line 5,981 ⟶ 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}}
<
@seen_numbers = Set.new
Line 5,994 ⟶ 6,679:
@seen_numbers << n
digit_squared_sum = n.
if happy?(digit_squared_sum)
Line 6,002 ⟶ 6,687:
false # Return false
end
end</
Helper method to produce output:
<
happy_numbers = []
Line 6,016 ⟶ 6,701:
end
print_happy</
{{out}}
<
===Alternative version===
<
def happy(n)
sum = n.
return @memo[sum] if @memo[sum]==0 or @memo[sum]==1
@memo[sum] = 0 # for the cycle check
Line 6,039 ⟶ 6,724:
for i in 99999999999900..99999999999999
puts i if happy(i)==1
end</
{{out}}
Line 6,068 ⟶ 6,753:
===Simpler Alternative===
{{trans|Python}}
<
past = []
until n == 1
Line 6,081 ⟶ 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) }</
{{out}}
<pre>
Line 6,105 ⟶ 6,790:
99999999999965
99999999999973</pre>
=={{header|Rust}}==
In Rust, using a tortoise/hare cycle detection algorithm (generic for integer types)
<
fn sumsqd(mut n: i32) -> i32 {
Line 6,173 ⟶ 6,828:
println!("{:?}", happy)
}</
{{out}}
<pre>
Line 6,180 ⟶ 6,835:
=={{header|Salmon}}==
<
outer:
iterate(x; [1...+oo])
Line 6,208 ⟶ 6,863:
now := new;
};
};</
This Salmon program produces the following output:
<pre>1 is happy.
Line 6,220 ⟶ 6,875:
=={{header|Scala}}==
<
| new Iterator[Int] {
| val seen = scala.collection.mutable.Set[Int]()
Line 6,244 ⟶ 6,899:
28
31
</syntaxhighlight>
=={{header|Scheme}}==
<
(do ((num num (quotient num 10))
(lst '() (cons (remainder num 10) lst)))
Line 6,263 ⟶ 6,918:
(cond ((= more 0) (newline))
((happy? n) (display " ") (display n) (loop (+ n 1) (- more 1)))
(else (loop (+ n 1) more))))</
The output is:
<pre>happy numbers: 1 7 10 13 19 23 28 31</pre>
Line 6,275 ⟶ 6,930:
=={{header|Seed7}}==
<
const type: cacheType is hash [integer] boolean;
Line 6,316 ⟶ 6,971:
end if;
end for;
end func;</
Output:
Line 6,334 ⟶ 6,989:
=={{header|SequenceL}}==
<
import <Utilities/Conversion.sl>;
Line 6,360 ⟶ 7,015:
true when n = 1
else
isHappyHelper(newN, cache ++ [n]);</
{{out}}
Line 6,369 ⟶ 7,024:
=={{header|SETL}}==
<
s := [n];
while n > 1 loop
Line 6,378 ⟶ 7,033:
end while;
return true;
end proc;</
<
n := 1;
until #happy = 8 loop
Line 6,386 ⟶ 7,041:
end loop;
print(happy);</
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Alternative version:
<
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
=={{header|Sidef}}==
<
static seen = Hash()
Line 6,405 ⟶ 7,060:
}
say happy.first(8)</
{{out}}
Line 6,416 ⟶ 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.
<
|cache negativeCache|
HappyNumber class >> new [ |me|
Line 6,478 ⟶ 7,133:
]
]
].</
<
happy := HappyNumber new.
Line 6,485 ⟶ 7,140:
(happy isHappy: i)
ifTrue: [ i displayNl ]
].</
Output:
1
Line 6,498 ⟶ 7,153:
an alternative version is:
{{works with|Smalltalk/X}}
<
next :=
Line 6,522 ⟶ 7,177:
try := try + 1
].
happyNumbers printCR</
Output:
OrderedCollection(1 7 10 13 19 23 28 31)
=={{header|Swift}}==
<
var cycle = [Int]()
Line 6,551 ⟶ 7,206:
}
count++
}</
{{out}}
<pre>
Line 6,565 ⟶ 7,220:
=={{header|Tcl}}==
using code from [[Sum of squares#Tcl]]
<
set seen [list]
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
Line 6,580 ⟶ 7,235:
incr n
}
puts "the first 8 happy numbers are: [list $happy]"</
<pre>the first 8 happy numbers are: {1 7 10 13 19 23 28 31}</pre>
=={{header|TUSCRIPT}}==
<
SECTION check
IF (n!=1) THEN
Line 6,619 ⟶ 7,274:
DO check
ENDLOOP
ENDLOOP</
Output:
<pre>
Line 6,632 ⟶ 7,287:
</pre>
=={{header|
{{works with|Uiua|0.10.0-dev.1}}
<syntaxhighlight lang="Uiua">
HC ← /+ⁿ2≡⋕°⋕ # Happiness calc = sum of squares of digits
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.
↙8⊚>0≡Happy⇡10000
# But iterative approach is still much faster
NH ← |1 ⟨NH|∘⟩≠0Happy.+1 # Find next Happy number
⇌[⍥(NH.) 7 1]
</syntaxhighlight>
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
<syntaxhighlight lang="bash">function sum_of_square_digits {
while (( n )); do
done
}
function is_happy
typeset -i n=$1
while (( n != 1 )); do
if [[ -n
return 1
fi
seen[$n]=1
done
return 0
}
function first_n_happy {
typeset -i count=$1 n
if is_happy "$n"; then
printf '%d\n' "$n"
(( count -= 1 ))
done
return 0
}
first_n_happy 8</
=={{header|Ursala}}==
Line 6,753 ⟶ 7,344:
and first(p) defines a function mapping a number n to the first n
positive naturals having property p.
<
#import nat
Line 6,762 ⟶ 7,353:
#cast %nL
main = (first happy) 8</
output:
<pre><1,7,10,13,19,23,28,31></pre>
Line 6,768 ⟶ 7,359:
=={{header|Vala}}==
{{libheader|Gee}}
<
/* function to sum the square of the digits */
Line 6,813 ⟶ 7,404:
stdout.printf("%d ", num);
stdout.printf("\n");
} // end main</
The output is:
<pre>
Line 6,819 ⟶ 7,410:
</pre>
=={{header|
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn happy(h int) bool {
mut m := map[int]bool{}
mut n := h
Line 7,021 ⟶ 7,437:
}
println('')
}</
{{out}}
<pre>
Line 7,029 ⟶ 7,445:
=={{header|Wren}}==
{{trans|Go}}
<
var m = {}
while (n > 1) {
Line 7,054 ⟶ 7,470:
n = n + 1
}
System.print()</
{{out}}
Line 7,068 ⟶ 7,484:
numbers.
<
int Inx; \index for List
include c:\cxpl\codes;
Line 7,112 ⟶ 7,528:
N0:= N0+1; \next starting number
until C=8; \done when 8 happy numbers have been found
]</
Output:
Line 7,127 ⟶ 7,543:
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
Line 7,164 ⟶ 7,580:
return s;
}
</syntaxhighlight>
{{Out}}
<pre>
Line 7,172 ⟶ 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}}
<
foreach N in ([1..]){
n:=N; while(1){
Line 7,180 ⟶ 7,596:
}
}
}</
<
h.walk(8).println();</
{{out}}
<pre>L(1,7,10,13,19,23,28,31)</pre>
Get the one million-th happy number. Nobody would call this quick.
<
{{out}}<pre>7105849</pre>
|