Happy numbers: Difference between revisions
m
→{{header|Uiua}}: slightly nicer algorithm
Alextretyak (talk | contribs) m (→{{header|11l}}) |
m (→{{header|Uiua}}: slightly nicer algorithm) |
||
(83 intermediate revisions by 36 users not shown) | |||
Line 1:
{{task|Arithmetic operations}}
From Wikipedia, the free encyclopedia:
:: A [[wp:Happy number|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 stay), or it loops endlessly in a cycle which does not include '''1'''.
<br>
:: Those numbers for which this process end in '''1''' are ''happy'' numbers,
:: while those numbers that do <u>not</u> end in '''1''' are ''unhappy'' numbers.
;
Find and print the first '''8''' happy numbers.
Display an example of your output here on this page.
;Related tasks:
* [[Iterated digits squaring]]
;See also:
* The OEIS entry: [[oeis:A007770|The happy numbers: A007770]]
* The OEIS entry: [[oeis:A031177|The unhappy numbers; A031177]]
<br><br>
Line 20 ⟶ 27:
{{trans|Python}}
<
Set[Int] past
L n != 1
Line 29 ⟶ 36:
R 1B
print((0.<500).filter(x -> happy(x))[0.<8])</
{{out}}
Line 35 ⟶ 42:
[1, 7, 10, 13, 19, 23, 28, 31]
</pre>
=={{header|8080 Assembly}}==
This is not just a demonstration of 8080 assembly, but also of why it pays to look closely at the problem domain.
The following program only does 8-bit unsigned integer math, which not only fits the 8080's instruction set very well,
it also means the cycle detection can be done using only an array of 256 flags, and all other state
fits in the registers. This makes the program a good deal simpler than it would've been otherwise.
In general, 8-bit math is not good enough for numerical problems, but in this particular case,
the problem only asks for the first eight happy numbers, none of which (nor any of the unhappy numbers
in between) have a cycle that ever goes above 145, so eight bits is good enough. In fact, for any input
under 256, the cycle never goes above 163; this program could be trivially changed to print up to 39 happy numbers.
<syntaxhighlight 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
org 100h
lxi d,0108h ; D=current number to test, E=amount of numbers
;;; Is D happy?
number: mvi a,1 ; We haven't seen any numbers yet, set flags to 1
lxi h,256*flags
init: mov m,a
inr l
jnz init
mov a,d ; Get digits
step: call digits
mov l,a ; L = D1 * D1
mov h,a
xra a
sqr1: add h
dcr l
jnz sqr1
mov l,a
mov h,b ; L += D10 * D10
xra a
sqr10: add h
dcr b
jnz sqr10
add l
mov l,a
mov h,c ; L += D100 * D100
xra a
sqr100: add h
dcr c
jnz sqr100
add l
mov l,a
mvi h,flags ; Look up corresponding flag
dcr m ; Will give 0 the first time and not-0 afterwards
mov a,l ; If we haven't seen the number before, another step
jz step
dcr l ; If we _had_ seen it, then is it 1?
jz happy ; If so, it is happy
next: inr d ; Afterwards, try next number
jmp number
happy: mov a,d ; D is happy - get its digits (for output)
lxi h,string+3
call digits ; Write digits into string for output
call sdgt ; Ones digit,
mov a,b ; Tens digit,
call sdgt
mov a,c ; Hundreds digit
call sdgt
push d ; Keep counters on stack
mvi c,puts ; Print string using CP/M call
xchg
call bdos
pop d ; Restore counters
dcr e ; One fewer happy number left
jnz next ; If we need more, do the next one
ret
;;; Store A as ASCII digit in [HL] and go to previous digit
sdgt: adi '0'
dcx h
mov m,a
ret
;;; Get digits of 8-bit number in A.
;;; Input: A = number
;;; Output: C=100s digit, B=10s digit, A=1s digit
digits: lxi b,-1 ; Set B and C to -1 (correct for extra loop cycle)
d100: inr c ; Calculate hundreds digit
sui 100 ; By trial subtraction of 100
jnc d100 ; Until underflow occurs
adi 100 ; Loop runs one cycle too many, so add 100 back
d10: inr b ; Calculate 10s digit in the same way
sui 10
jnc d10
adi 10
ret ; 1s digit is left in A afterwards
string: db '000',13,10,'$'</syntaxhighlight>
{{out}}
<pre>001
007
010
013
019
023
028
031</pre>
=={{header|8th}}==
<
: until! "not while!" eval i;
Line 67 ⟶ 176:
;with
;with
</syntaxhighlight>
{{out}}
<pre>
Line 74 ⟶ 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 99 ⟶ 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!}}==
<syntaxhighlight lang="action!">BYTE FUNC SumOfSquares(BYTE x)
BYTE sum,d
sum=0
WHILE x#0
DO
d=x MOD 10
d==*d
sum==+d
x==/10
OD
RETURN (sum)
BYTE FUNC Contains(BYTE ARRAY a BYTE count,x)
BYTE i
FOR i=0 TO count-1
DO
IF a(i)=x THEN RETURN (1) FI
OD
RETURN (0)
BYTE FUNC IsHappyNumber(BYTE x)
BYTE ARRAY cache(100)
BYTE count
count=0
WHILE x#1
DO
cache(count)=x
count==+1
x=SumOfSquares(x)
IF Contains(cache,count,x) THEN
RETURN (0)
FI
OD
RETURN (1)
PROC Main()
BYTE x,count
x=1 count=0
WHILE count<8
DO
IF IsHappyNumber(x) THEN
count==+1
PrintF("%I: %I%E",count,x)
FI
x==+1
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Happy_numbers.png Screenshot from Atari 8-bit computer]
<pre>
1: 1
2: 7
3: 10
4: 13
5: 19
6: 23
7: 28
8: 31
</pre>
=={{header|ActionScript}}==
<
{
var sum:uint = 0;
Line 145 ⟶ 353:
}
}
printHappy();</
Sample output:
<pre>
Line 159 ⟶ 367:
=={{header|Ada}}==
<
with Ada.Containers.Ordered_Sets;
Line 199 ⟶ 407:
end if;
end loop;
end Test_Happy_Digits;</
Sample output:
<pre>
Line 209 ⟶ 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 233 ⟶ 441:
print((i, new line))
FI
OD</
Output:
<pre>
Line 245 ⟶ 453:
+31
</pre>
=={{header|ALGOL-M}}==
<syntaxhighlight lang="algolm">begin
integer function mod(a,b);
integer a,b;
mod := a-(a/b)*b;
integer function sumdgtsq(n);
integer n;
sumdgtsq :=
if n = 0 then 0
else mod(n,10)*mod(n,10) + sumdgtsq(n/10);
integer function happy(n);
integer n;
begin
integer i;
integer array seen[0:200];
for i := 0 step 1 until 200 do seen[i] := 0;
while seen[n] = 0 do
begin
seen[n] := 1;
n := sumdgtsq(n);
end;
happy := if n = 1 then 1 else 0;
end;
integer i, n;
i := n := 0;
while n < 8 do
begin
if happy(i) = 1 then
begin
write(i);
n := n + 1;
end;
i := i + 1;
end;
end</syntaxhighlight>
{{out}}
<pre> 1
7
10
13
19
23
28
31</pre>
=={{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 309 ⟶ 550:
===Tradfn===
<
[1] ⍝0: Happy number
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
Line 328 ⟶ 569:
[17]
[18] ⎕←~∘0¨∆first↑bin/iroof ⍝ Show ∆first numbers, but not 0
∇</
<pre>
HappyNumbers 100 8
Line 335 ⟶ 576:
===Dfn===
<syntaxhighlight lang="apl">
HappyNumbers←{ ⍝ return the first ⍵ Happy Numbers
⍺←⍬ ⍝ initial list
Line 350 ⟶ 591:
HappyNumbers 8
1 7 10 13 19 23 28 31
</syntaxhighlight>
=={{header|AppleScript}}==
===Iteration===
<
set howManyHappyNumbers to 8
set happyNumberList to {}
Line 386 ⟶ 627:
end repeat
return (numberToCheck = 1)
end isHappy</
<pre>
Result: (*1, 7, 10, 13, 19, 23, 28, 31*)
Line 394 ⟶ 635:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<
-- isHappy :: Int -> Bool
Line 434 ⟶ 675:
end isHappy
on run
Line 471 ⟶ 712:
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 484 ⟶ 725:
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
Line 497 ⟶ 739:
end mReturn
-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
set
{my text item delimiters, pat}
set xs to text items of src
set my text item delimiters to dlm
return xs
end splitOn
-- until :: (a -> Bool) -> (a -> a) -> a -> a
Line 516 ⟶ 761:
end tell
return v
end |until|</
{{Out}}
<
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">ord0: to :integer `0`
happy?: function [x][
n: x
past: new []
while [n <> 1][
s: to :string n
n: 0
loop s 'c [
i: (to :integer c) - ord0
n: n + i * i
]
if contains? past n -> return false
'past ++ n
]
return true
]
loop 0..31 'x [
if happy? x -> print x
]</syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
28
31</pre>
=={{header|AutoHotkey}}==
<
If isHappy(A_Index) {
out .= (out="" ? "" : ",") . A_Index
Line 541 ⟶ 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 563 ⟶ 845:
n := t, t := 0
}
}</
<pre>1 7 10 13 19 23 28 31</pre>
=={{
<
$c = 0
$k = 0
Line 590 ⟶ 872:
EndIf
WEnd
</syntaxhighlight>
<pre>
Line 606 ⟶ 888:
===Alternative version===
<
$c = 0
$k = 0
Line 631 ⟶ 913:
$a.Clear
WEnd
</syntaxhighlight>
<pre>
Saves all numbers in a list, duplicate entry indicates a loop.
Line 646 ⟶ 928:
=={{header|AWK}}==
<
{
if ( n in happy ) return 1;
Line 686 ⟶ 968:
}
}
}</
Result:
<pre>1
Line 701 ⟶ 983:
Alternately, for legibility one might write:
<
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
Line 728 ⟶ 1,010:
}
return tot
}</
=={{header|BASIC}}==
==={{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
while cnt < 8
if isHappy(n) = 1 then
cnt += 1
print cnt; " => "; n
end if
n += 1
end while
function isHappy(num)
isHappy = 0
cont = 0
while cont < 50 and isHappy <> 1
num$ = string(num)
cont += 1
isHappy = 0
for i = 1 to length(num$)
isHappy += int(mid(num$,i,1)) ^ 2
next i
num = isHappy
end while
end function</syntaxhighlight>
==={{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 812 ⟶ 1,661:
)
set /a n=sum
)</
Sample usage and output
<pre>
Line 870 ⟶ 1,719:
</pre>
=={{header|
<syntaxhighlight lang="bcpl">get "libhdr"
let sumdigitsq(n) =
n=0 -> 0, (n rem 10)*(n rem 10)+sumdigitsq(n/10)
let happy(n) = valof
$( let seen = vec 255
for i = 0 to 255 do
$( n!seen :=
$) repeatuntil
resultis
$)
let start() be
$( let n, i =
while n < 8
$( if
$)
wrch('*N')
$)</syntaxhighlight>
{{out}}
<pre>1 7
=={{header|Bori}}==
<
{
ints cache;
Line 939 ⟶ 1,784:
}
puts("First 8 happy numbers : " + str.newline + happynums);
}</
Output:
<pre>First 8 happy numbers :
[1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|BQN}}==
<syntaxhighlight lang="bqn">SumSqDgt ← +´2⋆˜ •Fmt-'0'˙
Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢
8↑Happy¨⊸/↕50</syntaxhighlight>
{{out}}
<pre>⟨ 1 7 10 13 19 23 28 31 ⟩</pre>
=={{header|Brat}}==
<
happiness = set.new 1
Line 973 ⟶ 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 981 ⟶ 1,833:
=={{header|C}}==
Recursively look up if digit square sum is happy.
<
#define CACHE 256
Line 1,013 ⟶ 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,047 ⟶ 1,899:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,194 ⟶ 1,950:
}
}
}</
<pre>
First 8 happy numbers : 1,7,10,13,19,23,28,31
Line 1,201 ⟶ 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,234 ⟶ 1,990:
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}</
{{out}}
<pre>---Happy Numbers---
Line 1,246 ⟶ 2,002:
The 10,000,000th: 71,313,350
Computation time 33.264518 seconds.</pre>
=={{header|C++}}==
{{trans|Python}}
<syntaxhighlight lang="cpp">#include <map>
#include <set>
bool happy(int number) {
static std::map<int, bool> cache;
std::set<int> cycle;
while (number != 1 && !cycle.count(number)) {
if (cache.count(number)) {
number = cache[number] ? 1 : 0;
break;
}
cycle.insert(number);
int newnumber = 0;
while (number > 0) {
int digit = number % 10;
newnumber += digit * digit;
number /= 10;
}
number = newnumber;
}
bool happiness = number == 1;
for (std::set<int>::const_iterator it = cycle.begin();
it != cycle.end(); it++)
cache[*it] = happiness;
return happiness;
}
#include <iostream>
int main() {
for (int i = 1; i < 50; i++)
if (happy(i))
std::cout << i << std::endl;
return 0;
}</syntaxhighlight>
Output:
<pre>1
7
10
13
19
23
28
31
32
44
49</pre>
Alternative version without caching:
<syntaxhighlight lang="cpp">unsigned int happy_iteration(unsigned int n)
{
unsigned int result = 0;
while (n > 0)
{
unsigned int lastdig = n % 10;
result += lastdig*lastdig;
n /= 10;
}
return result;
}
bool is_happy(unsigned int n)
{
unsigned int n2 = happy_iteration(n);
while (n != n2)
{
n = happy_iteration(n);
n2 = happy_iteration(happy_iteration(n2));
}
return n == 1;
}
#include <iostream>
int main()
{
unsigned int current_number = 1;
unsigned int happy_count = 0;
while (happy_count != 8)
{
if (is_happy(current_number))
{
std::cout << current_number << " ";
++happy_count;
}
++current_number;
}
std::cout << std::endl;
}</syntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Cycle detection in <code>is_happy()</code> above is done using [[wp:Floyd's cycle-finding algorithm|Floyd's cycle-finding algorithm]].
=={{header|Clojure}}==
<
(loop [n n, seen #{}]
(cond
Line 1,262 ⟶ 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,299 ⟶ 2,151:
(filter #(= :happy (happy-algo %)))))
(println (take 8 happy-numbers))</
Same output.
=={{header|CLU}}==
<syntaxhighlight lang="clu">sum_dig_sq = proc (n: int) returns (int)
sum_sq: int := 0
while n > 0 do
sum_sq := sum_sq + (n // 10) ** 2
n := n / 10
end
return (sum_sq)
end sum_dig_sq
is_happy = proc (n: int) returns (bool)
nn: int := sum_dig_sq(n)
while nn ~= n cand nn ~= 1 do
n := sum_dig_sq(n)
nn := sum_dig_sq(sum_dig_sq(nn))
end
return (nn = 1)
end is_happy
happy_numbers = iter (start, num: int) yields (int)
n: int := start
while num > 0 do
if is_happy(n) then
yield (n)
num := num-1
end
n := n+1
end
end happy_numbers
start_up = proc ()
po: stream := stream$primary_output()
for i: int in happy_numbers(1, 8) do
stream$putl(po, int$unparse(i))
end
end start_up </syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
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,324 ⟶ 2,290:
console.log i
cnt += 1
i += 1</
output
<pre>
Line 1,339 ⟶ 2,305:
=={{header|Common Lisp}}==
<
(* n n))
Line 1,360 ⟶ 2,326:
(print (happys))
</syntaxhighlight>
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
sub sumDigitSquare(n: uint8): (s: uint8) is
s := 0;
while n != 0 loop
var d := n % 10;
s := s + d * d;
n := n / 10;
end loop;
end sub;
sub isHappy(n: uint8): (h: uint8) is
var seen: uint8[256];
MemZero(&seen[0], @bytesof seen);
while seen[n] == 0 loop
seen[n] := 1;
n := sumDigitSquare(n);
end loop;
if n == 1 then
h := 1;
else
h := 0;
end if;
end sub;
var n: uint8 := 1;
var seen: uint8 := 0;
while seen < 8 loop
if isHappy(n) != 0 then
print_i8(n);
print_nl();
seen := seen + 1;
end if;
n := n + 1;
end loop;</syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
28
31</pre>
=={{header|Crystal}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">def happy?(n)
past = [] of Int32 | Int64
until n == 1
sum = 0; while n > 0; sum += (n % 10) ** 2; n //= 10 end
return false if past.includes? (n = sum)
past << n
end
true
end
i = count = 0
until count == 8; (puts i; count += 1) if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</syntaxhighlight>
{{out}}
<pre>
1
7
10
13
19
23
28
31
99999999999901
99999999999910
99999999999914
99999999999915
99999999999916
99999999999937
99999999999941
99999999999951
99999999999956
99999999999961
99999999999965
99999999999973</pre>
=={{header|D}}==
<
int[int] past;
Line 1,387 ⟶ 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,409 ⟶ 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,447 ⟶ 2,504:
i++;
}
}</
=={{header|dc}}==
<
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx</
Output:
<pre>1
Line 1,463 ⟶ 2,520:
28
31</pre>
=={{header|DCL}}==
<
$ found = 0
$ i = 1
Line 1,513 ⟶ 2,571:
$ goto loop1
$ done:
$ show symbol found*</
{{out}}
<pre> FOUND = 8 Hex = 00000008 Octal = 00000000010
Line 1,524 ⟶ 2,582:
FOUND_7 = 28 Hex = 0000001C Octal = 00000000034
FOUND_8 = 31 Hex = 0000001F Octal = 00000000037</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{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;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Int;
type
TIntegerDynArray = TArray<Integer>;
TIntHelper = record helper for Integer
function IsHappy: Boolean;
procedure Next;
end;
{ TIntHelper }
function TIntHelper.IsHappy: Boolean;
var
cache: TIntegerDynArray;
sum, n: integer;
begin
n := self;
repeat
sum := 0;
while n > 0 do
begin
sum := sum + (n mod 10) * (n mod 10);
n := n div 10;
end;
if sum = 1 then
exit(True);
if cache.Has(sum) then
exit(False);
n := sum;
cache.Add(sum);
until false;
end;
procedure TIntHelper.Next;
begin
inc(self);
end;
var
count, n: integer;
begin
n := 1;
count := 0;
while count < 8 do
begin
if n.IsHappy then
begin
count.Next;
write(n, ' ');
end;
n.Next;
end;
writeln;
readln;
end.</syntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec dsumsq(byte n) byte:
byte r, d;
r := 0;
while n~=0 do
d := n % 10;
n := n / 10;
r := r + d * d
od;
r
corp
proc nonrec happy(byte n) bool:
[256] bool seen;
byte i;
for i from 0 upto 255 do seen[i] := false od;
while not seen[n] do
seen[n] := true;
n := dsumsq(n)
od;
seen[1]
corp
proc nonrec main() void:
byte n, seen;
n := 1;
seen := 0;
while seen < 8 do
if happy(n) then
writeln(n:3);
seen := seen + 1
fi;
n := n + 1
od
corp</syntaxhighlight>
{{out}}
<pre> 1
7
10
13
19
23
28
31</pre>
=={{header|DWScript}}==
<
var
cache : array of Integer;
Line 1,603 ⟶ 2,728:
Dec(n);
end;
end;</
Output:
<pre>1
Line 1,616 ⟶ 2,741:
=={{header|Dyalect}}==
<
var m = []
while n > 1 {
m.
var x = n
n = 0
Line 1,627 ⟶ 2,752:
x /= 10
}
if m.
return false
}
Line 1,633 ⟶ 2,758:
return true
}
var (n, found) = (1, 0)
while found < 8 {
Line 1,642 ⟶ 2,767:
n += 1
}
print()</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">next-num:
0
while over:
over
* dup % swap 10
+
swap floor / swap 10 swap
drop swap
is-happy happies n:
if has happies n:
return happies! n
local :seq set{ n }
n
while /= 1 dup:
next-num
if has seq dup:
drop
set-to happies n false
return false
if has happies dup:
set-to happies n dup happies!
return
set-to seq over true
drop
set-to happies n true
true
local :h {}
1 0
while > 8 over:
if is-happy h dup:
!print( "A happy number: " over )
swap ++ swap
++
drop
drop</syntaxhighlight>
{{output}}
<pre>A happy number: 1
A happy number: 7
A happy number: 10
A happy number: 13
A happy number: 19
A happy number: 23
A happy number: 28
A happy number: 31</pre>
=={{header|E}}==
{{output?|E}}
<
var seen := [].asSet()
while (!seen.contains(x)) {
Line 1,669 ⟶ 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 1,744 ⟶ 2,952:
end
</syntaxhighlight>
=={{header|Elena}}==
{{trans|C#}}
ELENA
<
import system'collections;
import system'routines;
Line 1,759 ⟶ 2,968:
while (num != 1)
{
if (cache.indexOfElement
{
^ false
Line 1,766 ⟶ 2,975:
while (num != 0)
{
int digit := num.mod
sum += (digit*digit);
num /= 10
Line 1,791 ⟶ 3,000:
};
console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}</
{{out}}
<pre>
Line 1,798 ⟶ 3,007:
=={{header|Elixir}}==
<
def task(num) do
Process.put({:happy, 1}, true)
Line 1,824 ⟶ 3,033:
end
IO.inspect Happy.task(8)</
{{out}}
Line 1,832 ⟶ 3,041:
=={{header|Erlang}}==
<
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
Line 1,864 ⟶ 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 1,886 ⟶ 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 1,919 ⟶ 3,128:
end if
n += 1
end while</
Output:
<pre>1
Line 1,933 ⟶ 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 1,962 ⟶ 3,171:
|> Seq.truncate 8 // Stop when we've found 8
|> Seq.iter (Printf.printf "%d\n") // Print results
</syntaxhighlight>
Output:
<pre>
Line 1,976 ⟶ 3,185:
=={{header|Factor}}==
<
: squares ( n -- s )
Line 1,996 ⟶ 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,015 ⟶ 3,224:
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%</
{{out}}
Line 2,021 ⟶ 3,230:
=={{header|Fantom}}==
<
{
static Bool isHappy (Int n)
Line 2,056 ⟶ 3,265:
}
}
</syntaxhighlight>
Output:
<pre>
Line 2,069 ⟶ 3,278:
</pre>
=={{header|
<syntaxhighlight lang="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
01.40 I (J-8)1.2;Q
01.50 T N,!
01.60 S J=J+1
01.70 G 1.3
02.10 S A=K;S R=0
02.20 S B=FITR(A/10)
02.30 S R=R+(A-10*B)^2
02.40 S A=B
02.50 I (-A)2.2
03.10 F X=0,162;S S(X)=-1
03.20 S K=N
03.30 S S(K)=0
03.40 D 2;S K=R
03.50 I (S(K))3.3</syntaxhighlight>
{{out}}
<pre>= 1
= 7
= 10
= 13
= 19
= 23
= 28
= 31</pre>
=={{header|Forth}}==
<
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
Line 2,097 ⟶ 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,110 ⟶ 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,188 ⟶ 3,421:
end function is_happy
end program happy</
Output:
<pre>1
Line 2,198 ⟶ 3,431:
28
31</pre>
=={{header|Frege}}==
Line 2,262 ⟶ 3,437:
{{Works with|Frege|3.21.586-g026e8d7}}
<
import Prelude.Math
Line 2,278 ⟶ 3,453:
f = sum . map (sqr . digitToInteger) . unpacked . show
main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n</
{{out}}
Line 2,286 ⟶ 3,461:
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,316 ⟶ 3,552:
}
fmt.Println()
}</
{{out}}
<pre>
Line 2,323 ⟶ 3,559:
=={{header|Groovy}}==
<
def number = delegate as Long
def cycle = new HashSet<Long>()
Line 2,337 ⟶ 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,374 ⟶ 3,610:
AAdd( aUnhappy, nSum )
RETURN IsHappy( nSum )</
Output:
Line 2,381 ⟶ 3,617:
=={{header|Haskell}}==
<
import Data.Set (member, insert, empty)
Line 2,394 ⟶ 3,630:
main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]</
{{Out}}
<pre>1
Line 2,406 ⟶ 3,642:
We can create a cache for small numbers to greatly speed up the process:
<
happy :: Int -> Bool
Line 2,424 ⟶ 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 2,445 ⟶ 3,681:
if happy(n) then return i
}
end</
Usage and Output:
<pre>
Line 2,454 ⟶ 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 2,467 ⟶ 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 2,498 ⟶ 3,734:
}
}
}</
Output:
<pre>1
Line 2,513 ⟶ 3,749:
{{works with|Java|1.8}}
{{trans|Java}}
<
import java.util.Arrays;
Line 2,540 ⟶ 3,776:
return number == 1;
}
}</
Output:
<pre>1
Line 2,555 ⟶ 3,791:
===ES5===
====Iteration====
<
var m, digit ;
var cycle = [] ;
Line 2,580 ⟶ 3,816:
document.write(number + " ") ;
number++ ;
}</
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 2,587 ⟶ 3,823:
====Functional composition====
{{Trans|Haskell}}
<
// isHappy :: Int -> Bool
Line 2,646 ⟶ 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 2,721 ⟶ 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 2,741 ⟶ 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 2,754 ⟶ 3,990:
[0,0] | subtask;
happy($n|tonumber)</
{{out}}
<
1
7
Line 2,765 ⟶ 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 2,796 ⟶ 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 2,815 ⟶ 4,051:
Faster with use of cache
{{trans|C}}
<
buf = zeros(Int, CACHE)
buf[
function happy(n)
if n < CACHE
Line 2,824 ⟶ 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 2,853 ⟶ 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 2,866 ⟶ 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 2,881 ⟶ 4,118:
=={{header|Kotlin}}==
{{trans|C#}}
<
fun isHappy(n: Int): Boolean {
Line 2,910 ⟶ 4,147:
}
println("First 8 happy numbers : " + happyNums.joinToString(", "))
}</
{{out}}
Line 2,916 ⟶ 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 2,932 ⟶ 4,203:
where isHappy(#x)
take 8
select #x</
Output:
<
=={{header|Logo}}==
<
output (apply "sum (map [[d] d*d] ` :number))
end
Line 3,022 ⟶ 4,232:
print n_happy 8
bye</
Output:
Line 3,030 ⟶ 4,240:
{{works with|lci 0.10.3}}
<
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
Line 3,112 ⟶ 4,322:
OIC
IM OUTTA YR LOOP
KTHXBYE</
Output:<pre>1
Line 3,124 ⟶ 4,334:
=={{header|Lua}}==
<
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
Line 3,138 ⟶ 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,155 ⟶ 4,365:
<syntaxhighlight lang="m2000 interpreter">
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
Line 3,188 ⟶ 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
19
23
28
31</pre>
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
BOOLEAN CYCLE
DIMENSION CYCLE(200)
VECTOR VALUES OUTFMT = $I2*$
SEEN = 0
I = 0
NEXNUM THROUGH ZERO, FOR K=0, 1, K.G.200
ZERO CYCLE(K) = 0B
I = I + 1
SUMSQR = I
CHKLP N = SUMSQR
SUMSQR = 0
SUMLP DIG = N-N/10*10
SUMSQR = SUMSQR + DIG*DIG
N = N/10
WHENEVER N.NE.0, TRANSFER TO SUMLP
WHENEVER SUMSQR.E.1, TRANSFER TO HAPPY
WHENEVER CYCLE(SUMSQR), TRANSFER TO NEXNUM
CYCLE(SUMSQR) = 1B
TRANSFER TO CHKLP
HAPPY PRINT FORMAT OUTFMT,I
SEEN = SEEN+1
WHENEVER SEEN.L.8, TRANSFER TO NEXNUM
END OF PROGRAM
</syntaxhighlight>
{{out}}
<pre> 1
7
10
Line 3,202 ⟶ 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,209 ⟶ 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,236 ⟶ 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,254 ⟶ 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,269 ⟶ 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,294 ⟶ 4,617:
]
]
happynumbers</
gives back:
<
=={{header|MATLAB}}==
Recursive version:
<
nHappy = 0;
k = 1;
Line 3,321 ⟶ 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 3,353 ⟶ 4,709:
)
</syntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
1
7
Line 3,364 ⟶ 4,720:
28
31
</syntaxhighlight>
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 3,406 ⟶ 4,762:
:- func sqr(int) = int.
sqr(X) = X * X.</
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 3,412 ⟶ 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 3,431 ⟶ 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 3,473 ⟶ 4,861:
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
</syntaxhighlight>
Output:
<pre>1 is happy
Line 3,485 ⟶ 4,873:
9 is unhappy
10 is happy</pre>
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE HappyNumbers;
FROM InOut IMPORT WriteCard, WriteLn;
CONST Amount = 8;
VAR seen, num: CARDINAL;
PROCEDURE SumDigitSquares(n: CARDINAL): CARDINAL;
VAR sum, digit: CARDINAL;
BEGIN
sum := 0;
WHILE n>0 DO
digit := n MOD 10;
n := n DIV 10;
sum := sum + digit * digit;
END;
RETURN sum;
END SumDigitSquares;
PROCEDURE Happy(n: CARDINAL): BOOLEAN;
VAR i: CARDINAL;
seen: ARRAY [0..255] OF BOOLEAN;
BEGIN
FOR i := 0 TO 255 DO
seen[i] := FALSE;
END;
REPEAT
seen[n] := TRUE;
n := SumDigitSquares(n);
UNTIL seen[n];
RETURN seen[1];
END Happy;
BEGIN
seen := 0;
num := 0;
WHILE seen < Amount DO
IF Happy(num) THEN
INC(seen);
WriteCard(num,2);
WriteLn();
END;
INC(num);
END;
END HappyNumbers.</syntaxhighlight>
{{out}}
<pre> 1
7
10
13
19
23
28
31</pre>
=={{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 3,510 ⟶ 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 3,532 ⟶ 4,975:
=={{header|NetRexx}}==
{{trans|REXX}}
<
limit = arg[0] /*get argument for LIMIT. */
say limit
Line 3,559 ⟶ 5,002:
q=sum /*now, lets try the Q sum. */
end
end</
;Output
<pre>
Line 3,677 ⟶ 5,120:
=={{header|Nim}}==
{{trans|Python}}
<
proc happy(n: int): bool =
Line 3,696 ⟶ 5,139:
for x in 0..31:
if happy(x):
echo x</
Output:
<pre>1
Line 3,708 ⟶ 5,151:
=={{header|Objeck}}==
<
use Structure;
Line 3,754 ⟶ 5,197:
}
}
}</
output:
<pre>First 8 happy numbers: 1,7,10,13,19,23,28,31,</pre>
Line 3,760 ⟶ 5,203:
=={{header|OCaml}}==
Using [[wp:Cycle detection|Floyd's cycle-finding algorithm]].
<
let step =
Line 3,784 ⟶ 5,227:
List.iter print_endline (
List.rev_map string_of_num (first 8)) ;;</
Output:
<pre>$ ocaml nums.cma happy_numbers.ml
Line 3,798 ⟶ 5,241:
=={{header|Oforth}}==
<
| cycle |
ListBuffer new ->cycle
Line 3,813 ⟶ 5,256:
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;</
Output:
Line 3,819 ⟶ 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 3,851 ⟶ 5,328:
number = next
end
</syntaxhighlight>
<pre>
First 8 happy numbers are:
Line 3,865 ⟶ 5,342:
=={{header|Oz}}==
<
import
System
Line 3,908 ⟶ 5,385:
in
{System.show {List.take HappyNumbers 8}}
end</
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Line 3,915 ⟶ 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 3,924 ⟶ 5,401:
)
};
select(isHappy, vector(31,i,i))</
Output:
<pre>%1 = [1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|Pascal}}==
<
uses
Line 3,989 ⟶ 5,466:
end;
writeln;
end.</
Output:
<pre>:> ./HappyNumbers
Line 3,995 ⟶ 5,472:
</pre>
===alternative for counting fast===
{{works with|Free Pascal}}
The Cache is limited to maximum value of the sum of squared digits and filled up in a blink of an eye.Even for cDigit2=1e9 takes 0.7s.Calculation of sum of squared digits is improved.Saving this SqrdSumCache speeds up tremendous.
So i am able to check if the 1'000'000 th happy number is 7105849 as stated in C language.This seems to be true.
Extended to 10e18
Tested with Free Pascal 3.0.4
<syntaxhighlight lang="pascal">Program HappyNumbers (output);
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON,
{$ELSE}
{$APPLICATION CONSOLE}
{$ENDIF}
//{$DEFINE Use1E9}
uses
sysutils,//Timing
strutils;//Numb2USA
const
base = 10;
HighCache = 20*(sqr(base-1));//sum of sqr digit of Uint64
{$IFDEF Use1E9}
cDigit1 = sqr(base)*sqr(base);//must be power of base
cDigit2 = Base*sqr(cDigit1);// 1e9
cMaxPot = 18;
{$ELSE}
cDigit1 = base*sqr(base);//must be power of base
cDigit2 = sqr(cDigit1);// 1e6
cMaxPot = 14;
{$ENDIF}
type
tSqrdSumCache = array[0..2*HighCache] of
var
SumSqrDgts :tSumSqrDgts;
Cache : tCache;
SqrdSumCache1,
SqrdSumCache2 :tSqrdSumCache;
T1,T0 : TDateTime;
MAX2,Max1 : NativeInt;
procedure InitSumSqrDgts;
//calc all sum of squared digits 0..cDigits2
//using already calculated values
var
i,j,n,sq,Base1:
begin
SumSqrDgts[i] := i*i;
Base1 := Base;
repeat
For i := 1 to base-1 do
Begin
sq := SumSqrDgts[i];
For j := 0 to base1-1 do
Begin
SumSqrDgts[n] := sq+SumSqrDgts[j];
inc(n);
end;
end;
Base1 := Base1*base;
until Base1 >= cDigit2;
SumSqrDgts[n] := 1;
end;
function SumSqrdDgt(n: Uint64):NativeUint;inline;
var
begin
while n>cDigit2 do
Begin
n :=
inc(result,SumSqrDgts[r]);
inc(result,SumSqrDgts[n]);
end;
procedure CalcSqrdSumCache1;
var
Count : tSqrdSumCache;
i,sq,result : NativeInt;
begin
For i :=High(Count) downto 0 do
Count[i] := 0;
//count the manifold
For i := cDigit1-1 downto 0 do
inc(count[SumSqrDgts[i]]);
For i := High(Count) downto 0 do
if count[i] <> 0 then
Begin
Max1 := i;
BREAK;
end;
For sq := 0 to (20-3)*81 do
Begin
result := 0;
For i := Max1 downto 0 do
inc(result,Count[i]*Cache[sq+i]);
SqrdSumCache1[sq] := result;
end;
end;
procedure CalcSqrdSumCache2;
var
i,sq,result : NativeInt;
begin
For i := cDigit2-1 downto 0 do
inc(count[SumSqrDgts[i]]);
For
Begin
Max2 := i;
BREAK;
end;
For sq := 0 to (20-6)*81 do
Begin
result := 0;
For i := Max2 downto 0 do
inc(result,Count[i]*Cache[sq+i]);
SqrdSumCache2[sq] := result;
end;
end;
procedure Inithappy;
Line 4,071 ⟶ 5,610:
n,s,p : NativeUint;
Begin
fillchar(
fillchar(SqrdSumCache2,SizeOf(SqrdSumCache2),#0);
InitSumSqrDgts;
fillChar(Cache,SizeOf(Cache),#0);
Cache[1] := 1;
For n := 1 to High(Cache) do
Line 4,101 ⟶ 5,642:
end;
end;
//mark all unhappy numbers with 0
For n := 1 to High(Cache) do
If Cache[n] <> 1 then
Cache[n] := 0;
CalcSqrdSumCache1;
CalcSqrdSumCache2;
end;
function is_happy(n: NativeUint): boolean;inline;
begin
is_happy := Boolean(Cache[SumSqrdDgt(n)]
end;
function nthHappy(Limit:
var
d,e,sE: NativeUint;
begin
sE := SumSqrDgts[e];
//big steps
while Limit >= cDigit2 do
begin
dec(Limit,SqrdSumCache2[SumSqrDgts[d]+sE]);
inc(result,cDigit2);
inc(d);
inc(
sE := SumSqrdDgt(e);//SumSqrDgts[e];
end;
end;
//small steps
while Limit >= cDigit1 do
Begin
dec(Limit,SqrdSumCache1[SumSqrdDgt(result)]);
inc(result,cDigit1);
end;
//ONE BY ONE
while Limit > 0 do
begin
dec(Limit,Cache[SumSqrdDgt(result)]);
inc(result);
end;
result -= 1;
end;
var
n, count
Limit: NativeUint;
begin
write('cDigit1 = ',Numb2USA(IntToStr(cDigit1)));
writeln(' cDigit2 = ',Numb2USA(IntToStr(cDigit2)));
T0 := now;
Inithappy;
writeln('Init takes ',FormatDateTime(' HH:NN:SS.ZZZ',now-T0));
n := 1;
count := 0;
while count <
begin
if is_happy(n) then
Line 4,162 ⟶ 5,713:
writeln;
T0 := now;
T1 := T0;
n := 1;
Limit := 10;
repeat
writeln('
FormatDateTime(' HH:NN:SS.ZZZ',now-T1));
T1 := now;
inc(n);
Limit := limit*10;
until n>
writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0));
end.
</syntaxhighlight>
;output:
<pre>
cDigit1 = 1,000 cDigit2 = 1,000,000
Init takes 00:00:00.004
1E 8 n.th happy number 698,739,425 00:00:00.000
1E 9 n.th happy number 6,788,052,776 00:00:00.000
1E10 n.th happy number 66,305,148,869 00:00:00.000
1E11 n.th happy number 660,861,957,662 00:00:00.001
1E12 n.th happy number 6,745,877,698,967 00:00:00.008
1E13 n.th happy number 70,538,879,028,725 00:00:00.059
1E14 n.th happy number 744,083,563,164,178 00:00:00.612
Total time counting 00:00:00.680
real 0m0
cDigit1 = 10,000 cDigit2 = 1,000,000,000
Init takes 00:00:02.848
1 7 10 13 19 23 28 31 32 44
1E 1 n.th happy number 44 00:00:00.000
1E 2 n.th happy number 694 00:00:00.000
1E 3 n.th happy number 6,899 00:00:00.000
1E 4 n.th happy number 67,169 00:00:00.000
1E 5 n.th happy number 692,961 00:00:00.000
1E 6 n.th happy number 7,105,849 00:00:00.000
1E 7 n.th happy number 71,313,350 00:00:00.000
1E 8 n.th happy number 698,739,425 00:00:00.001
1E 9 n.th happy number 6,788,052,776 00:00:00.008
1E10 n.th happy number 66,305,148,869 00:00:00.010
1E11 n.th happy number 660,861,957,662 00:00:00.009
1E12 n.th happy number 6,745,877,698,967 00:00:00.008
1E13 n.th happy number 70,538,879,028,725 00:00:00.008
1E14 n.th happy number 744,083,563,164,178 00:00:00.011
1E15 n.th happy number 7,888,334,045,397,315 00:00:00.019
1E16 n.th happy number 82,440,929,809,838,249 00:00:00.079
1E17 n.th happy number 845,099,936,580,193,833 00:00:00.698
1E18 n.th happy number 8,489,964,903,498,345,213 00:00:06.920
Total time counting 00:00:07.771
real 0m10,627s
</pre>
=={{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 4,204 ⟶ 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>
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|
<
sub is_happy {
my ($n) = @_;
Line 4,222 ⟶ 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>
=={{header|Phix}}==
Copy of [[Happy_numbers#Euphoria|Euphoria]] tweaked to give a one-line output
<!--<syntaxhighlight lang="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>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">seen</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">k</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">),</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">k</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">seen</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">false</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">8</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">is_happy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 4,301 ⟶ 5,848:
=={{header|PHP}}==
{{trans|D}}
<
while (1) {
$total = 0;
Line 4,324 ⟶ 5,871:
}
$i++;
}</
<pre>1 7 10 13 19 23 28 31 </pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
println(happy_len(8)).
happy(N) =>
S = [N],
Happy = 1,
while (Happy == 1, N > 1)
N := sum([to_integer(I)**2 : I in N.to_string()]),
if member(N,S) then
Happy := 0
else
S := S ++ [N]
end
end,
Happy == 1.
happy_len(Limit) = S =>
S = [],
N = 1,
while (S.length < Limit)
if happy(N) then
S := S ++ [N]
end,
N := N + 1
end.</syntaxhighlight>
{{out}}
<pre>[1,7,10,13,19,23,28,31]</pre>
=={{header|PicoLisp}}==
<
(let Seen NIL
(loop
Line 4,340 ⟶ 5,917:
(do 8
(until (happy? (inc 'H)))
(printsp H) ) )</
Output:
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|PILOT}}==
<syntaxhighlight lang="pilot">C :max=8
:n=0
:i=0
*test
U :*happy
T (a=1):#n
C (a=1):i=i+1
C :n=n+1
J (i<max):*test
E :
*happy
C :a=n
:x=n
U :*sumsq
C :b=s
*loop
C :x=a
U :*sumsq
C :a=s
C :x=b
U :*sumsq
C :x=s
U :*sumsq
C :b=s
J (a<>b):*loop
E :
*sumsq
C :s=0
*digit
C :y=x/10
:z=x-y*10
:s=s+z*#z
:x=y
J (x):*digit
E :</syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
28
31</pre>
=={{header|PL/I}}==
<
declare (i, j, n, m, nh initial (0) ) fixed binary (31);
Line 4,369 ⟶ 5,994:
end;
end test;
</syntaxhighlight>
OUTPUT:
<pre>
Line 4,381 ⟶ 6,006:
31 is a happy number
</pre>
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
/* FIND SUM OF SQUARE OF DIGITS OF NUMBER */
DIGIT$SQUARE: PROCEDURE (N) BYTE;
DECLARE (N, T, D) BYTE;
T = 0;
DO WHILE N > 0;
D = N MOD 10;
T = T + D * D;
N = N / 10;
END;
RETURN T;
END DIGIT$SQUARE;
/* CHECK IF NUMBER IS HAPPY */
HAPPY: PROCEDURE (N) BYTE;
DECLARE (N, I) BYTE;
DECLARE FLAG (256) BYTE;
DO I=0 TO 255;
FLAG(I) = 0;
END;
DO WHILE NOT FLAG(N);
FLAG(N) = 1;
N = DIGIT$SQUARE(N);
END;
RETURN N = 1;
END HAPPY;
/* CP/M BDOS CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
/* PRINT STRING */
PRINT: PROCEDURE (STR);
DECLARE STR ADDRESS;
CALL BDOS(9, STR);
END PRINT;
/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('...',13,10,'$');
DECLARE P ADDRESS;
DECLARE (N, C BASED P) BYTE;
P = .S(3);
DIGIT:
P = P - 1;
C = (N MOD 10) + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* FIND FIRST 8 HAPPY NUMBERS */
DECLARE SEEN BYTE INITIAL (0);
DECLARE N BYTE INITIAL (1);
DO WHILE SEEN < 8;
IF HAPPY(N) THEN DO;
CALL PRINT$NUMBER(N);
SEEN = SEEN + 1;
END;
N = N + 1;
END;
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre>1
7
10
13
19
23
28
31</pre>
=={{header|Potion}}==
<
isHappy = (n) :
Line 4,402 ⟶ 6,109:
if (isHappy(i)): firstEight append(i).
.
firstEight string print</
=={{header|PowerShell}}==
<
$a=@()
for($i=2;$a.count -lt $n;$i++) {
Line 4,424 ⟶ 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 4,477 ⟶ 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 4,539 ⟶ 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 4,622 ⟶ 6,284:
if __name__ == '__main__':
main()</
{{Out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">
[ 0 swap
[ 10 /mod 2 **
rot + swap
dup 0 = until ]
drop ] is digitsquare ( n --> n )
[ [ digitsquare
dup 1 != while
dup 42 != while
again ]
1 = ] is happy ( n --> b )
[ [] 1
[ dip
[ 2dup size > ]
swap while
dup happy if
[ tuck join swap ]
1+ again ]
drop nip ] is happies ( n --> [ )
8 happies echo</syntaxhighlight>
{{Out}}
<pre>[ 1 7 10 13 19 23 28 31 ]</pre>
=={{header|R}}==
<
{
stopifnot(is.numeric(n) && length(n)==1)
Line 4,655 ⟶ 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 4,672 ⟶ 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 4,697 ⟶ 6,389:
x))
(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)</
=={{header|
(formerly Perl 6)
{{works with|rakudo|2015-09-13}}
<syntaxhighlight lang="raku" line>sub happy (Int $n is copy --> Bool) {
loop {
state %seen;
$n = [+] $n.comb.map: { $_ ** 2 }
return True if $n == 1;
return False if %seen{$n}++;
}
}
say join ' ', grep(&happy, 1 .. *)[^8];</syntaxhighlight>
{{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" line>my @happy = lazy gather for 1..* -> $number {
my %stopper = 1 =>
my $n = $number;
repeat until %stopper{$n}++ {
$n = [+] $n.comb X** 2;
}
take $number if $n == 1;
}
say ~@happy[^8];</syntaxhighlight>
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" line>subset Happy of Int where sub ($n) {
$n == 1 ?? True !!
$n < 7 ?? False !!
&?ROUTINE([+] $n.comb »**» 2);
}
say (grep Happy, 1 .. *)[^8];</syntaxhighlight>
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
set lasty = 0
set found = " "
while y != 1 and not (found regex "\s".y."\s")
set found = found . y . " "
set m = 0
while y > 0
set digit = y mod 10
set m = m + digit * digit
set y = (y - digit) / 10
end while
set y = format(m,"%1d")
end while
set found = found . y . " "
if y = 1
set result = 1
else
set result = 0
end if
end function
set c = 0
set i = 1
while c < 8 and i < 100
if happy(i)
echo i
set c = c + 1
end if
set i = i + 1
end while
</syntaxhighlight>
<pre>
1
Line 4,732 ⟶ 6,514:
</pre>
=={{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
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: /* output management */
Parse Arg hn /* the happy number */
End
Else /* otherwise */
ol=ol hn
Return
help:
Say 'rexx hno n compute and show the first n happy numbers'
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 high
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 4,914 ⟶ 6,632:
End
Return True
</syntaxhighlight>
{{out}}
<pre>
Line 4,927 ⟶ 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 4,940 ⟶ 6,679:
@seen_numbers << n
digit_squared_sum = n.
if happy?(digit_squared_sum)
Line 4,948 ⟶ 6,687:
false # Return false
end
end</
Helper method to produce output:
<
happy_numbers = []
Line 4,962 ⟶ 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 4,985 ⟶ 6,724:
for i in 99999999999900..99999999999999
puts i if happy(i)==1
end</
{{out}}
Line 5,012 ⟶ 6,751:
</pre>
===Simpler Alternative===
{{trans|Python}}
<syntaxhighlight lang="ruby">def happy?(n)
until n == 1
n = n.digits.sum { |d| d * d }
return false if past.include? n
past << n
end
true
end
i = count = 0
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</syntaxhighlight>
{{out}}
<pre>
1
7
10
13
19
23
28
31
99999999999901
99999999999910
99999999999914
99999999999915
99999999999916
99999999999937
99999999999941
99999999999951
99999999999956
99999999999961
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 5,079 ⟶ 6,828:
println!("{:?}", happy)
}</
{{out}}
<pre>
Line 5,086 ⟶ 6,835:
=={{header|Salmon}}==
<
outer:
iterate(x; [1...+oo])
Line 5,114 ⟶ 6,863:
now := new;
};
};</
This Salmon program produces the following output:
<pre>1 is happy.
Line 5,126 ⟶ 6,875:
=={{header|Scala}}==
<
| new Iterator[Int] {
| val seen = scala.collection.mutable.Set[Int]()
Line 5,150 ⟶ 6,899:
28
31
</syntaxhighlight>
=={{header|Scheme}}==
<
(do ((num num (quotient num 10))
(lst '() (cons (remainder num 10) lst)))
Line 5,169 ⟶ 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 5,181 ⟶ 6,930:
=={{header|Seed7}}==
<
const type: cacheType is hash [integer] boolean;
Line 5,222 ⟶ 6,971:
end if;
end for;
end func;</
Output:
Line 5,237 ⟶ 6,986:
44
49
</pre>
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">import <Utilities/Math.sl>;
import <Utilities/Conversion.sl>;
main(argv(2)) := findHappys(stringToInt(head(argv)));
findHappys(count) := findHappysHelper(count, 1, []);
findHappysHelper(count, n, happys(1)) :=
happys when size(happys) = count
else
findHappysHelper(count, n + 1, happys ++ [n]) when isHappy(n)
else
findHappysHelper(count, n + 1, happys);
isHappy(n) := isHappyHelper(n, []);
isHappyHelper(n, cache(1)) :=
let
digits[i] := (n / integerPower(10, i - 1)) mod 10
foreach i within 1 ... ceiling(log(10, n + 1));
newN := sum(integerPower(digits, 2));
in
false when some(n = cache)
else
true when n = 1
else
isHappyHelper(newN, cache ++ [n]);</syntaxhighlight>
{{out}}
<pre>
$>happy.exe 8
[1,7,10,13,19,23,28,31]
</pre>
=={{header|SETL}}==
<
s := [n];
while n > 1 loop
Line 5,249 ⟶ 7,033:
end while;
return true;
end proc;</
<
n := 1;
until #happy = 8 loop
Line 5,257 ⟶ 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 5,276 ⟶ 7,060:
}
say happy.first(8)</
{{out}}
<pre>
[1, 7, 10, 13, 19, 23, 28, 31]
</pre>
Line 5,322 ⟶ 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 5,384 ⟶ 7,133:
]
]
].</
<
happy := HappyNumber new.
Line 5,391 ⟶ 7,140:
(happy isHappy: i)
ifTrue: [ i displayNl ]
].</
Output:
1
Line 5,404 ⟶ 7,153:
an alternative version is:
{{works with|Smalltalk/X}}
<
next :=
Line 5,428 ⟶ 7,177:
try := try + 1
].
happyNumbers printCR</
Output:
OrderedCollection(1 7 10 13 19 23 28 31)
=={{header|Swift}}==
<
var cycle = [Int]()
Line 5,456 ⟶ 7,206:
}
count++
}</
{{out}}
<pre>
Line 5,470 ⟶ 7,220:
=={{header|Tcl}}==
using code from [[Sum of squares#Tcl]]
<
set seen [list]
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
Line 5,485 ⟶ 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 5,524 ⟶ 7,274:
DO check
ENDLOOP
ENDLOOP</
Output:
<pre>
Line 5,537 ⟶ 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 5,658 ⟶ 7,344:
and first(p) defines a function mapping a number n to the first n
positive naturals having property p.
<
#import nat
Line 5,667 ⟶ 7,353:
#cast %nL
main = (first happy) 8</
output:
<pre><1,7,10,13,19,23,28,31></pre>
Line 5,673 ⟶ 7,359:
=={{header|Vala}}==
{{libheader|Gee}}
<
/* function to sum the square of the digits */
Line 5,718 ⟶ 7,404:
stdout.printf("%d ", num);
stdout.printf("\n");
} // end main</
The output is:
<pre>
Line 5,724 ⟶ 7,410:
</pre>
=={{header|
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn happy(h int) bool {
mut m := map[int]bool{}
mut n := h
for n > 1 {
m[n] = true
mut x := 0
for x, n = n, 0; x > 0; x /= 10 {
d := x % 10
n += d * d
}
if m[n] {
return false
}
}
return true
}
fn main() {
for found, n := 0, 1; found < 8; n++ {
if happy(n) {
print("$n ")
found++
}
}
println('')
}</syntaxhighlight>
{{out}}
<pre>
1 7 10 13 19 23 28 31
</pre>
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="wren">var happy = Fn.new { |n|
var m = {}
while (n > 1) {
m[n] = true
var x = n
n = 0
while (x > 0) {
var d = x % 10
n = n + d*d
x = (x/10).floor
}
if (m[n] == true) return false // m[n] will be null if 'n' is not a key
}
return true
}
var found = 0
var n = 1
while (found < 8) {
if (happy.call(n)) {
System.write("%(n) ")
found = found + 1
}
n = n + 1
}
System.print()</syntaxhighlight>
{{out}}
<pre>
</pre>
=={{header|XPL0}}==
Line 5,906 ⟶ 7,484:
numbers.
<
int Inx; \index for List
include c:\cxpl\codes;
Line 5,950 ⟶ 7,528:
N0:= N0+1; \next starting number
until C=8; \done when 8 happy numbers have been found
]</
Output:
Line 5,964 ⟶ 7,542:
</pre>
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
pub fn main() !void {
try stdout.print("The first 8 happy numbers are: ", .{});
var n: u32 = 1;
var c: u4 = 0;
while (c < 8) {
if (isHappy(n)) {
c += 1;
try stdout.print("{} ", .{n});
}
n += 1;
}
try stdout.print("\n", .{});
}
fn isHappy(n: u32) bool {
var t = n;
var h = sumsq(n);
while (t != h) {
t = sumsq(t);
h = sumsq(sumsq(h));
}
return t == 1;
}
fn sumsq(n0: u32) u32 {
var s: u32 = 0;
var n = n0;
while (n > 0) : (n /= 10) {
const m = n % 10;
s += m * m;
}
return s;
}
</syntaxhighlight>
{{Out}}
<pre>
The first 8 happy numbers are: 1 7 10 13 19 23 28 31
</pre>
=={{header|zkl}}==
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 5,975 ⟶ 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>
|