Happy Numbers - Rosetta Code
Happy Numbers - Rosetta Code
(/wiki/Rosetta_Code)
I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited
open invite to RC's Slack. (https://join.slack.com/t/rosettacode/shared_invite/zt-glwmugtu-xpMPcqHs0u6MsK5zCmJF~Q). --
Michael Mol (/wiki/User:Short_Circuit) (talk (/wiki/User_talk:Short_Circuit)) 20:59, 30 May 2020 (UTC)
Happy numbers
From Wikipedia, the free encyclopedia:
https://rosettacode.org/wiki/Happy_numbers 1/210
4/4/2021 Happy numbers - Rosetta Code
See also
The OEIS entry: The happy numbers: A007770 (https://oeis.org/A007770)
The OEIS entry: The unhappy numbers; A031177 (https://oeis.org/A031177)
Contents
1 11l
2 8080 Assembly
3 8th
4 ACL2
5 ActionScript
6 Ada
7 ALGOL 68
8 ALGOL W
9 APL
9.1 Tradfn
9.2 Dfn
10 AppleScript
10.1 Iteration
10.2 Functional composition
11 AutoHotkey
11.1 Alternative version
12 AutoIt
12.1 Alternative version
13 AWK
13.1 Alternative version
14 Batch File
15 BBC BASIC
16 Bori
17 Brat
18 C
19 C#
19.1 Alternate (cacheless)
20 C++
21 Clojure
21.1 Alternate Version (with caching)
22 CoffeeScript
23 Common Lisp
https://rosettacode.org/wiki/Happy_numbers 2/210
4/4/2021 Happy numbers - Rosetta Code
24 Cowgol
25 Crystal
26 D
26.1 Alternative Version
27 Dart
28 dc
29 DCL
30 Delphi
31 DWScript
32 Dyalect
33 Déjà Vu
34 E
35 Eiffel
36 Elena
37 Elixir
38 Erlang
39 Euphoria
40 F#
41 Factor
42 FALSE
43 Fantom
44 FOCAL
45 Forth
45.1 Lookup Table
46 Fortran
47 FreeBASIC
48 Frege
49 Fōrmulæ
50 Go
51 Groovy
52 Harbour
53 Haskell
54 Icon and Unicon
55 J
56 Java
56.1 Java 1.8
57 JavaScript
57.1 ES5
57.1.1 Iteration
https://rosettacode.org/wiki/Happy_numbers 3/210
4/4/2021 Happy numbers - Rosetta Code
57.2 ES6
57.2.1 Functional composition
58 jq
59 Julia
60 K
61 Kotlin
62 Lasso
63 Liberty BASIC
64 Locomotive Basic
65 Logo
66 LOLCODE
67 Lua
68 M2000 Interpreter
69 MAD
70 Maple
71 Mathematica / Wolfram Language
72 MATLAB
73 MAXScript
74 Mercury
75 MiniScript
76 ML
76.1 mLite
77 MUMPS
78 NetRexx
79 Nim
80 Objeck
81 OCaml
82 Oforth
83 ooRexx
84 Oz
85 PARI/GP
86 Pascal
86.1 alternative for counting fast
87 Perl
88 Phix
89 PHP
90 PicoLisp
91 PL/I
92 Potion
https://rosettacode.org/wiki/Happy_numbers 4/210
4/4/2021 Happy numbers - Rosetta Code
93 PowerShell
94 Prolog
95 PureBasic
96 Python
96.1 Procedural
96.2 Composition of pure functions
97 Quackery
98 R
99 Racket
100 Raku
101 Relation
102 REXX
102.1 unoptimized
102.2 optimized, vertical list
102.3 optimized, horizontal list
103 Ring
104 Ruby
104.1 Alternative version
104.2 Simpler Alternative
105 Run BASIC
106 Rust
107 Salmon
108 Scala
109 Scheme
110 Scratch
111 Seed7
112 SequenceL
113 SETL
114 Sidef
115 Smalltalk
116 Swift
117 Tcl
118 TUSCRIPT
119 uBasic/4tH
120 UNIX Shell
121 Ursala
122 Vala
123 VBA
124 VBScript
https://rosettacode.org/wiki/Happy_numbers 5/210
4/4/2021 Happy numbers - Rosetta Code
11l (/wiki/Category:11l)
Translation of: Python
F happy(=n)
Set[Int] past
L n != 1
n = sum(String(n).map(с -> Int(с)^2))
I n C past
R 0B
past.add(n)
R 1B
Output:
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.
https://rosettacode.org/wiki/Happy_numbers 6/210
4/4/2021 Happy numbers - Rosetta Code
https://rosettacode.org/wiki/Happy_numbers 7/210
4/4/2021 Happy numbers - Rosetta Code
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,'$'
Output:
https://rosettacode.org/wiki/Happy_numbers 8/210
4/4/2021 Happy numbers - Rosetta Code
001
007
010
013
019
023
028
031
8th (/wiki/Category:8th)
https://rosettacode.org/wiki/Happy_numbers 9/210
4/4/2021 Happy numbers - Rosetta Code
with: w
with: n
: sumsqd \ n -- n
0 swap repeat
0; 10 /mod -rot sqr + swap
again ;
: cycle \ n xt -- n
>r
dup r@ exec \ -- tortoise, hare
repeat
swap r@ exec
swap r@ exec r@ exec
2dup = until!
rdrop drop ;
: .happy \ n --
1 repeat
dup happy? if dup . space swap 1- swap then 1+
over 0 > while!
2drop cr ;
;with
;with
Output:
ok> 8 .happy
1 7 10 13 19 23 28 31
ACL2 (/wiki/Category:ACL2)
https://rosettacode.org/wiki/Happy_numbers 10/210
4/4/2021 Happy numbers - Rosetta Code
(defun first-happy-nums-r (n i)
(cond ((zp n) nil)
((is-happy i)
(cons i (first-happy-nums-r (1- n) (1+ i))))
(t (first-happy-nums-r n (1+ i)))))
Output:
(1 7 10 13 19 23 28 31)
ActionScript (/wiki/Category:ActionScript)
https://rosettacode.org/wiki/Happy_numbers 11/210
4/4/2021 Happy numbers - Rosetta Code
function sumOfSquares(n:uint)
{
var sum:uint = 0;
while(n != 0)
{
sum += (n%10)*(n%10);
n /= 10;
}
return sum;
}
function isInArray(n:uint, array:Array)
{
for(var k = 0; k < array.length; k++)
if(n == array[k]) return true;
return false;
}
function isHappy(n)
{
var sequence:Array = new Array();
while(n != 1)
{
sequence.push(n);
n = sumOfSquares(n);
if(isInArray(n,sequence))return false;
}
return true;
}
function printHappy()
{
var numbersLeft:uint = 8;
var numberToTest:uint = 1;
while(numbersLeft != 0)
{
if(isHappy(numberToTest))
{
trace(numberToTest);
numbersLeft--;
}
numberToTest++;
}
}
printHappy();
https://rosettacode.org/wiki/Happy_numbers 12/210
4/4/2021 Happy numbers - Rosetta Code
Sample output:
1
7
10
13
19
23
28
31
Ada (/wiki/Category:Ada)
https://rosettacode.org/wiki/Happy_numbers 13/210
4/4/2021 Happy numbers - Rosetta Code
procedure Test_Happy_Digits is
function Is_Happy (N : Positive) return Boolean is
package Sets_Of_Positive is new Ada.Containers.Ordered_Sets (Positive);
use Sets_Of_Positive;
function Next (N : Positive) return Natural is
Sum : Natural := 0;
Accum : Natural := N;
begin
while Accum > 0 loop
Sum := Sum + (Accum mod 10) ** 2;
Accum := Accum / 10;
end loop;
return Sum;
end Next;
Current : Positive := N;
Visited : Set;
begin
loop
if Current = 1 then
return True;
elsif Visited.Contains (Current) then
return False;
else
Visited.Insert (Current);
Current := Next (Current);
end if;
end loop;
end Is_Happy;
Found : Natural := 0;
begin
for N in Positive'Range loop
if Is_Happy (N) then
Put (Integer'Image (N));
Found := Found + 1;
exit when Found = 8;
end if;
end loop;
end Test_Happy_Digits;
Sample output:
https://rosettacode.org/wiki/Happy_numbers 14/210
4/4/2021 Happy numbers - Rosetta Code
1 7 10 13 19 23 28 31
ALGOL 68 (/wiki/Category:ALGOL_68)
Works with: ALGOL 68 (/wiki/ALGOL_68) version Standard - no extensions to language used
Works with: ALGOL 68G (/wiki/ALGOL_68G) version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 (/wiki/ELLA_ALGOL_68) version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
INT count := 0;
FOR i WHILE count NE num happy DO
IF is happy(i) THEN
count +:= 1;
print((i, new line))
FI
OD
Output:
https://rosettacode.org/wiki/Happy_numbers 15/210
4/4/2021 Happy numbers - Rosetta Code
+1
+7
+10
+13
+19
+23
+28
+31
ALGOL W (/wiki/Category:ALGOL_W)
https://rosettacode.org/wiki/Happy_numbers 16/210
4/4/2021 Happy numbers - Rosetta Code
begin
% find some happy numbers %
% returns true if n is happy, false otherwise; n must be >= 0 %
logical procedure isHappy( integer value n ) ;
if n < 2 then true
else begin
% seen is used to hold the values of the cycle of the %
% digit square sums, as noted in the Batch File %
% version, we do not need a large array. The digit %
% square sum of 9 999 999 999 is 810... %
integer array seen( 0 :: 32 );
integer number, trys;
number := n;
trys := -1;
while begin
logical terminated;
integer tPos;
terminated := false;
tPos := 0;
while not terminated and tPos <= trys do begin
terminated := seen( tPos ) = number;
tPos := tPos + 1
end while_not_terminated_and_tPos_lt_trys ;
number > 1 and not terminated
end do begin
integer sum;
trys := trys + 1;
seen( trys ) := number;
sum := 0;
while number > 0 do begin
integer digit;
digit := number rem 10;
number := number div 10;
sum := sum + ( digit * digit )
end while_number_gt_0 ;
number := sum
end while_number_gt_1_and_not_terminated ;
number = 1
end isHappy ;
% print the first 8 happy numbers %
begin
integer happyCount, n;
happyCount := 0;
https://rosettacode.org/wiki/Happy_numbers 17/210
4/4/2021 Happy numbers - Rosetta Code
n := 1;
write( "first 8 happy numbers: " );
while happyCount < 8 do begin
if isHappy( n ) then begin
writeon( i_w := 1, " ", n );
happyCount := happyCount + 1
end if_isHappy_n ;
n := n + 1
end while_happyCount_lt_8
end
end.
Output:
APL (/wiki/Category:APL)
Tradfn
∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
[1] ⍝0: Happy number
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
[3] ⎕IO←1 ⍝ Index origin
[4] ∆roof ∆first←2↑arg,10 ⍝
[5]
[6] bin←{
[7] ⍺←⍬ ⍝ Default left arg
[8] ⍵=1:1 ⍝ Always happy!
[9]
[10] numbers←⍎¨1⊂⍕⍵ ⍝ Split numbers into parts
[11] next←+/{⍵*2}¨numbers ⍝ Sum and square of numbers
[12]
[13] next∊⍺:0 ⍝ Return 0, if already exists
[14] (⍺,next)∇ next ⍝ Check next number (recursive)
[15]
[16] }¨iroof←⍳∆roof ⍝ Does all numbers upto ∆root smiles?
[17]
[18] ⎕←~∘0¨∆first↑bin/iroof ⍝ Show ∆first numbers, but not 0
∇
https://rosettacode.org/wiki/Happy_numbers 18/210
4/4/2021 Happy numbers - Rosetta Code
HappyNumbers 100 8
1 7 10 13 19 23 28 31
Dfn
AppleScript (/wiki/Category:AppleScript)
Iteration
https://rosettacode.org/wiki/Happy_numbers 19/210
4/4/2021 Happy numbers - Rosetta Code
on run
set howManyHappyNumbers to 8
set happyNumberList to {}
set globalCounter to 1
on isHappy(numberToCheck)
set localCycle to {}
repeat while (numberToCheck ≠ 1)
if localCycle contains numberToCheck then
exit repeat
end if
set end of localCycle to numberToCheck
set tempNumber to 0
repeat while (numberToCheck > 0)
set digitOfNumber to numberToCheck mod 10
set tempNumber to tempNumber + (digitOfNumber ^ 2)
set numberToCheck to (numberToCheck - digitOfNumber) / 10
end repeat
set numberToCheck to tempNumber
end repeat
return (numberToCheck = 1)
end isHappy
Functional composition
Translation of: JavaScript
Translation of: Haskell
https://rosettacode.org/wiki/Happy_numbers 20/210
4/4/2021 Happy numbers - Rosetta Code
on |λ|(n)
foldl(digitSquared, 0, splitOn("", n as string))
end |λ|
end script
endsInOne's |λ|({}, n)
end isHappy
https://rosettacode.org/wiki/Happy_numbers 21/210
4/4/2021 Happy numbers - Rosetta Code
on |λ|(rec)
length of xs of rec = target of seriesLength
end |λ|
end script
script testResult
on |λ|(x)
if isHappy(x) then
xs & x
else
xs
end if
end |λ|
end script
https://rosettacode.org/wiki/Happy_numbers 22/210
4/4/2021 Happy numbers - Rosetta Code
return v
end tell
end foldl
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn
tell mReturn(f)
repeat until mp's |λ|(v)
set v to |λ|(v)
end repeat
end tell
return v
end |until|
Output:
https://rosettacode.org/wiki/Happy_numbers 23/210
4/4/2021 Happy numbers - Rosetta Code
AutoHotkey (/wiki/Category:AutoHotkey)
Loop (http://www.autohotkey.com/docs/commands/Loop.htm) {
If isHappy(A_Index (http://www.autohotkey.com/docs/Variables.htm#A_Index)) {
out .= (out="" ? "" : ",") . A_Index (http://www.autohotkey.com/docs/Variables.htm#A_Index)
i ++
If (i = 8) {
MsgBox (http://www.autohotkey.com/docs/commands/MsgBox.htm), The first 8 happy numbers are: %out%
ExitApp (http://www.autohotkey.com/docs/commands/ExitApp.htm)
}
}
}
isHappy(num, list="") {
list .= (list="" ? "" : ",") . num
Loop (http://www.autohotkey.com/docs/commands/Loop.htm), Parse, num
sum += A_LoopField (http://www.autohotkey.com/docs/Variables.htm#A_LoopField) ** 2
If (sum = 1)
Return true
Else If sum in %list%
Return false
Else Return isHappy(sum, list)
}
Alternative version
https://rosettacode.org/wiki/Happy_numbers 24/210
4/4/2021 Happy numbers - Rosetta Code
while h < 8
if (Happy(A_Index (http://www.autohotkey.com/docs/Variables.htm#A_Index))) {
Out .= A_Index (http://www.autohotkey.com/docs/Variables.htm#A_Index) A_Space (http://www.autohotkey.com/docs/Variables.htm#A_
h++
}
MsgBox (http://www.autohotkey.com/docs/commands/MsgBox.htm), % Out
Happy(n) {
Loop (http://www.autohotkey.com/docs/commands/Loop.htm), {
Loop (http://www.autohotkey.com/docs/commands/Loop.htm), Parse, n
t += A_LoopField (http://www.autohotkey.com/docs/Variables.htm#A_LoopField) ** 2
if (t = 89)
return, 0
if (t = 1)
return, 1
n := t, t := 0
}
}
1 7 10 13 19 23 28 31
AutoIt (/wiki/Category:AutoIt)
https://rosettacode.org/wiki/Happy_numbers 25/210
4/4/2021 Happy numbers - Rosetta Code
$c = 0
$k = 0
While (https://www.autoitscript.com/autoit3/docs/keywords.htm) $c < 8
$k += 1
$n = $k
While (https://www.autoitscript.com/autoit3/docs/keywords.htm) $n <> 1
$s = StringSplit (https://www.autoitscript.com/autoit3/docs/functions/StringSplit.htm)($n, "")
$t = 0
For (https://www.autoitscript.com/autoit3/docs/keywords.htm) $i = 1 To (https://www.autoitscript.com/autoit3/docs/keyw
$t += $s[$i] ^ 2
Next (https://www.autoitscript.com/autoit3/docs/keywords.htm)
$n = $t
Switch (https://www.autoitscript.com/autoit3/docs/keywords.htm) $n
Case (https://www.autoitscript.com/autoit3/docs/keywords.htm) 4,16,37,58,89,145,42,20
ExitLoop (https://www.autoitscript.com/autoit3/docs/keywords.htm)
EndSwitch (https://www.autoitscript.com/autoit3/docs/keywords.htm)
WEnd (https://www.autoitscript.com/autoit3/docs/keywords.htm)
If (https://www.autoitscript.com/autoit3/docs/keywords.htm) $n = 1 Then (https://www.autoitscript.com/autoit3/docs/keywords.ht
ConsoleWrite (https://www.autoitscript.com/autoit3/docs/functions/ConsoleWrite.htm)($k & " is Happy" & @CRLF (https://
$c += 1
EndIf (https://www.autoitscript.com/autoit3/docs/keywords.htm)
WEnd (https://www.autoitscript.com/autoit3/docs/keywords.htm)
Alternative version
https://rosettacode.org/wiki/Happy_numbers 26/210
4/4/2021 Happy numbers - Rosetta Code
$c = 0
$k = 0
While (https://www.autoitscript.com/autoit3/docs/keywords.htm) $c < 8
$a = ObjCreate (https://www.autoitscript.com/autoit3/docs/functions/ObjCreate.htm)("System.Collections.ArrayList")
$k += 1
$n = $k
While (https://www.autoitscript.com/autoit3/docs/keywords.htm) $n <> 1
If (https://www.autoitscript.com/autoit3/docs/keywords.htm) $a.Contains($n) Then (https://www.autoitscript.com/autoit3
ExitLoop (https://www.autoitscript.com/autoit3/docs/keywords.htm)
EndIf (https://www.autoitscript.com/autoit3/docs/keywords.htm)
$a.add($n)
$s = StringSplit (https://www.autoitscript.com/autoit3/docs/functions/StringSplit.htm)($n, "")
$t = 0
For (https://www.autoitscript.com/autoit3/docs/keywords.htm) $i = 1 To (https://www.autoitscript.com/autoit3/docs/keyw
$t += $s[$i] ^ 2
Next (https://www.autoitscript.com/autoit3/docs/keywords.htm)
$n = $t
WEnd (https://www.autoitscript.com/autoit3/docs/keywords.htm)
If (https://www.autoitscript.com/autoit3/docs/keywords.htm) $n = 1 Then (https://www.autoitscript.com/autoit3/docs/keywords.ht
ConsoleWrite (https://www.autoitscript.com/autoit3/docs/functions/ConsoleWrite.htm)($k & " is Happy" & @CRLF (https://
$c += 1
EndIf (https://www.autoitscript.com/autoit3/docs/keywords.htm)
$a.Clear
WEnd (https://www.autoitscript.com/autoit3/docs/keywords.htm)
AWK (/wiki/Category:AWK)
https://rosettacode.org/wiki/Happy_numbers 27/210
4/4/2021 Happy numbers - Rosetta Code
function is_happy(n)
{
if ( n in happy ) return 1;
if ( n in unhappy ) return 0;
cycle[""] = 0
while( (n!=1) && !(n in cycle) ) {
cycle[n] = n
new_n = 0
while(n>0) {
d = n % 10
new_n += d*d
n = int(n/10)
}
n = new_n
}
if ( n == 1 ) {
for (i_ in cycle) {
happy[cycle[i_]] = 1
delete cycle[i_]
}
return 1
} else {
for (i_ in cycle) {
unhappy[cycle[i_]] = 1
delete cycle[i_]
}
return 0
}
}
BEGIN {
cnt = 0
happy[""] = 0
unhappy[""] = 0
for(j=1; (cnt < 8); j++) {
if ( is_happy(j) == 1 ) {
cnt++
print j
}
}
}
Result:
https://rosettacode.org/wiki/Happy_numbers 28/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
Alternative version
Alternately, for legibility one might write:
BEGIN {
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
print i;
}
}
exit
}
https://rosettacode.org/wiki/Happy_numbers 29/210
4/4/2021 Happy numbers - Rosetta Code
https://rosettacode.org/wiki/Happy_numbers 30/210
4/4/2021 Happy numbers - Rosetta Code
:listInternal
:: This loop sequentially tests each number >= n. The loop conditionally
:: breaks within the body once cnt happy numbers have been found, or if
:: the max integer value is reached. Performance is improved by using a
:: FOR loop to perform most of the looping, with a GOTO only needed once
:: per 100 iterations.
for (https://www.ss64.com/nt/for.html) %%. in (https://www.ss64.com/nt/in.html) (
%L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10%
) do (https://www.ss64.com/nt/do.html) (
call (https://www.ss64.com/nt/call.html) :testInternal !n! && (
echo (https://www.ss64.com/nt/echo.html) !n!
https://rosettacode.org/wiki/Happy_numbers 31/210
4/4/2021 Happy numbers - Rosetta Code
:testInternal n
:: This routine loops until the sum of squared digits converges on 1 (happy)
:: or it detects a cycle (sad). It exits with errorlevel 0 for happy and 1 for sad.
:: Performance is improved by using a FOR loop for the looping instead of a GOTO.
:: Numbers less than 1000 never neeed more than 20 iterations, and any number
:: with 4 or more digits shrinks by at least one digit each iteration.
:: Since Windows batch can't handle more than 10 digits, allowance for 27
:: iterations is enough, and 30 is more than adequate.
setlocal (https://www.ss64.com/nt/setlocal.html)
set (https://www.ss64.com/nt/set.html) n=%1
for (https://www.ss64.com/nt/for.html) %%. in (https://www.ss64.com/nt/in.html) (%L10% %L10% %L10%) do (https://www.ss64.com/nt/do.h
if (https://www.ss64.com/nt/if.html) !n!==1 exit (https://www.ss64.com/nt/exit.html) /b 0
%= Only numbers < 1000 can cycle =%
if (https://www.ss64.com/nt/if.html) !n! lss (https://www.ss64.com/nt/lss.html) 1000 (
if (https://www.ss64.com/nt/if.html) defined (https://www.ss64.com/nt/defined.html) t.!n! exit (https://www.ss64.com/nt/exit.htm
set (https://www.ss64.com/nt/set.html) t.!n!=1
)
%= Sum the squared digits =%
%= Batch can't handle numbers greater than 10 digits so we can use =%
%= a constrained FOR (https://www.ss64.com/nt/for.html) loop and avoid a slow goto (https://www.ss64.com/nt/goto.html)
set (https://www.ss64.com/nt/set.html) sum=0
for (https://www.ss64.com/nt/for.html) /l %%N in (https://www.ss64.com/nt/in.html) (1 1 10) do (https://www.ss64.com/nt/do.html) (
if (https://www.ss64.com/nt/if.html) !n! gtr (https://www.ss64.com/nt/gtr.html) 0 set (https://www.ss64.com/nt/set.html) /a "sum
)
set (https://www.ss64.com/nt/set.html) /a n=sum
)
https://rosettacode.org/wiki/Happy_numbers 32/210
4/4/2021 Happy numbers - Rosetta Code
>happy list 1 8
1
7
10
13
19
23
28
31
>happy test 30
30 is sad :(
>happy test 31
31 is happy :)
>happy test 1 10
1 is happy :)
2 is sad :(
3 is sad :(
4 is sad :(
5 is sad :(
6 is sad :(
7 is happy :)
8 is sad :(
9 is sad :(
10 is happy :)
https://rosettacode.org/wiki/Happy_numbers 33/210
4/4/2021 Happy numbers - Rosetta Code
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)
Output:
https://rosettacode.org/wiki/Happy_numbers 34/210
4/4/2021 Happy numbers - Rosetta Code
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
Bori (/wiki/Category:Bori)
https://rosettacode.org/wiki/Happy_numbers 35/210
4/4/2021 Happy numbers - Rosetta Code
while (n != 1)
{
int sum = 0;
if (cache.contains(n))
return false;
cache.add(n);
while (n != 0)
{
int digit = n % 10;
sum += (digit * digit);
n = (int)(n / 10);
}
n = sum;
}
return true;
}
void test ()
{
int num = 1;
ints happynums;
Output:
https://rosettacode.org/wiki/Happy_numbers 36/210
4/4/2021 Happy numbers - Rosetta Code
Brat (/wiki/Category:Brat)
include :set
happiness = set.new 1
sadness = set.new
sum_of_squares_of_digits = { num |
num.to_s.dice.reduce 0 { sum, n | sum = sum + n.to_i ^ 2 }
}
num = 1
happies = []
num = num + 1
}
Output:
First eight happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]
Happy numbers found: [1, 7, 10, 13, 19, 23, 28, 31, 49, 68, 82, 97, 100, 130]
Sad numbers found: [2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17, 18, 20, 21, 22, 24, 25, 26, 27, 29, 30, 34, 36, 37, 40, 41, 42, 45, 5
C (/wiki/Category:C)
https://rosettacode.org/wiki/Happy_numbers 37/210
4/4/2021 Happy numbers - Rosetta Code
#include <stdio.h>
int happy(int n)
{
int sum = 0, x, nn;
if (n < CACHE) {
if (buf[n]) return 2 - buf[n];
buf[n] = h_no;
}
x = happy(sum);
if (n < CACHE) buf[n] = 2 - x;
return x;
}
int main()
{
int i, cnt = 8;
for (i = 1; cnt || !printf (https://www.opengroup.org/onlinepubs/009695399/functions/printf.html)("\n"); i++)
if (happy(i)) --cnt, printf (https://www.opengroup.org/onlinepubs/009695399/functions/printf.html)("%d ", i);
return 0;
}
output
1 7 10 13 19 23 28 31
The 1000000th happy number: 7105849
https://rosettacode.org/wiki/Happy_numbers 38/210
4/4/2021 Happy numbers - Rosetta Code
#include <stdio.h>
int dsum(int n)
{
int sum, x;
for (sum = 0; n; n /= 10) x = n % 10, sum += x * x;
return sum;
}
int happy(int n)
{
int nn;
while (n > 999) n = dsum(n); /* 4 digit numbers can't cycle */
nn = dsum(n);
while (nn != n && nn != 1)
n = dsum(n), nn = dsum(dsum(nn));
return n == 1;
}
int main()
{
int i, cnt = 8;
for (i = 1; cnt || !printf (https://www.opengroup.org/onlinepubs/009695399/functions/printf.html)("\n"); i++)
if (happy(i)) --cnt, printf (https://www.opengroup.org/onlinepubs/009695399/functions/printf.html)("%d ", i);
return 0;
}
C# (/wiki/Category:C_sharp)
https://rosettacode.org/wiki/Happy_numbers 39/210
4/4/2021 Happy numbers - Rosetta Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HappyNums
{
class Program
{
public static bool ishappy(int n)
{
List<int> cache = new (https://www.google.com/search?q=new+msdn.microsoft.com) List<int>();
int sum = 0;
while (n != 1)
{
if (cache.Contains(n))
{
return false;
}
cache.Add(n);
while (n != 0)
{
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
n = sum;
sum = 0;
}
return true;
}
https://rosettacode.org/wiki/Happy_numbers 40/210
4/4/2021 Happy numbers - Rosetta Code
num++;
}
Console.WriteLine("First 8 happy numbers : " + string.Join(",", happynums));
}
}
}
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.
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).
https://rosettacode.org/wiki/Happy_numbers 41/210
4/4/2021 Happy numbers - Rosetta Code
using System;
using System.Collections.Generic;
class Program
{
Output:
https://rosettacode.org/wiki/Happy_numbers 42/210
4/4/2021 Happy numbers - Rosetta Code
---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 33.264518 seconds.
C++ (/wiki/Category:C%2B%2B)
Translation of: Python
https://rosettacode.org/wiki/Happy_numbers 43/210
4/4/2021 Happy numbers - Rosetta Code
#include <map>
#include <set>
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;
}
Output:
https://rosettacode.org/wiki/Happy_numbers 44/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
32
44
49
https://rosettacode.org/wiki/Happy_numbers 45/210
4/4/2021 Happy numbers - Rosetta Code
#include <iostream>
int main()
{
unsigned int current_number = 1;
Output:
https://rosettacode.org/wiki/Happy_numbers 46/210
4/4/2021 Happy numbers - Rosetta Code
1 7 10 13 19 23 28 31
Cycle detection in is_happy() above is done using Floyd's cycle-finding algorithm (https://en.wikipedia.org/wiki/Floyd%27s_cycle-finding_algorithm).
Clojure (/wiki/Category:Clojure)
(defn happy? [n]
(loop [n n, seen #{}]
(cond
(= n 1) true
(seen n) false
:else
(recur (->> (str n)
(map #(Character/digit % 10))
(map #(* % %))
(reduce +))
(conj seen n)))))
Output:
(1 7 10 13 19 23 28 31)
https://rosettacode.org/wiki/Happy_numbers 47/210
4/4/2021 Happy numbers - Rosetta Code
(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})})
Same output.
CoffeeScript (/wiki/Category:CoffeeScript)
https://rosettacode.org/wiki/Happy_numbers 48/210
4/4/2021 Happy numbers - Rosetta Code
i = 1
cnt = 0
while cnt < 8
if happy(i)
console.log i
cnt += 1
i += 1
output
https://rosettacode.org/wiki/Happy_numbers 49/210
4/4/2021 Happy numbers - Rosetta Code
(print (happys))
Output:
(1 7 10 13 19 23 28 31)
Cowgol (/wiki/Category:Cowgol)
https://rosettacode.org/wiki/Happy_numbers 50/210
4/4/2021 Happy numbers - Rosetta Code
include "cowgol.coh";
if n == 1 then
h := 1;
else
h := 0;
end if;
end sub;
var n: uint8 := 1;
var seen: uint8 := 0;
Output:
https://rosettacode.org/wiki/Happy_numbers 51/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
Crystal (/wiki/Category:Crystal)
Translation of: 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) }
Output:
https://rosettacode.org/wiki/Happy_numbers 52/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
99999999999901
99999999999910
99999999999914
99999999999915
99999999999916
99999999999937
99999999999941
99999999999951
99999999999956
99999999999961
99999999999965
99999999999973
D (/wiki/Category:D)
https://rosettacode.org/wiki/Happy_numbers 53/210
4/4/2021 Happy numbers - Rosetta Code
while (true) {
int total = 0;
while (n > 0) {
total += (n % 10) ^^ 2;
n /= 10;
}
if (total == 1)
return true;
if (total in past)
return false;
n = total;
past[total] = 0;
}
}
void main() {
import std.stdio, std.algorithm, std.range;
int.max.iota.filter!isHappy.take(8).writeln;
}
Output:
Alternative Version
https://rosettacode.org/wiki/Happy_numbers 54/210
4/4/2021 Happy numbers - Rosetta Code
while (true) {
immutable t = n.text.representation.map!q{(a - '0') ^^ 2}.sum;
if (t == 1)
return true;
if (t in seen)
return false;
n = t;
seen[t] = 0;
}
}
void main() {
int.max.iota.filter!isHappy.take(8).writeln;
}
Same output.
Dart (/wiki/Category:Dart)
https://rosettacode.org/wiki/Happy_numbers 55/210
4/4/2021 Happy numbers - Rosetta Code
main() {
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
int count=0;
int i=0;
while(count<8) {
if(happy[i]==null) {
int j=i;
Set<int> sequence=new Set<int>();
while(happy[j]==null && !sequence.contains(j)) {
sequence.add(j);
int sum=0;
int val=j;
while(val>0) {
int digit=val%10;
sum+=digit*digit;
val=(val/10).toInt();
}
j=sum;
}
bool sequenceHappy=happy[j];
Iterator<int> it=sequence.iterator();
while(it.hasNext()) {
happy[it.next()]=sequenceHappy;
}
}
if(happy[i]) {
print(i);
count++;
}
i++;
}
}
dc (/wiki/Category:Dc)
https://rosettacode.org/wiki/Happy_numbers 56/210
4/4/2021 Happy numbers - Rosetta Code
[lcI~rscd*+lc0<H]sH
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx
Output:
1
7
10
13
19
23
28
31
DCL (/wiki/Category:DCL)
https://rosettacode.org/wiki/Happy_numbers 57/210
4/4/2021 Happy numbers - Rosetta Code
$ happy_1 = 1
$ found = 0
$ i = 1
$ loop1:
$ n = i
$ seen_list = ","
$ loop2:
$ if f$type( happy_'n ) .nes. "" then $ goto happy
$ if f$type( unhappy_'n ) .nes. "" then $ goto unhappy
$ if f$locate( "," + n + ",", seen_list ) .eq. f$length( seen_list )
$ then
$ seen_list = seen_list + f$string( n ) + ","
$ else
$ goto unhappy
$ endif
$ ns = f$string( n )
$ nl = f$length( ns )
$ j = 0
$ sumsq = 0
$ loop3:
$ digit = f$integer( f$extract( j, 1, ns ))
$ sumsq = sumsq + digit * digit
$ j = j + 1
$ if j .lt. nl then $ goto loop3
$ n = sumsq
$ goto loop2
$ unhappy:
$ j = 1
$ loop4:
$ x = f$element( j, ",", seen_list )
$ if x .eqs. "" then $ goto continue
$ unhappy_'x = 1
$ j = j + 1
$ goto loop4
$ happy:
$ found = found + 1
$ found_'found = i
$ if found .eq. 8 then $ goto done
$ j = 1
$ loop5:
$ x = f$element( j, ",", seen_list )
$ if x .eqs. "" then $ goto continue
$ happy_'x = 1
https://rosettacode.org/wiki/Happy_numbers 58/210
4/4/2021 Happy numbers - Rosetta Code
$ j = j + 1
$ goto loop5
$ continue:
$ i = i + 1
$ goto loop1
$ done:
$ show symbol found*
Output:
Delphi (/wiki/Category:Delphi)
Library: System.SysUtils (/wiki/Category:System.SysUtils)
Library: Boost.Int (/mw/index.php?title=Category:Boost.Int&action=edit&redlink=1)
Adaptation of #Pascal. The lib Boost.Int can be found here [1] (https://github.com/MaiconSoft/DelphiBoostLib)
https://rosettacode.org/wiki/Happy_numbers 59/210
4/4/2021 Happy numbers - Rosetta Code
program Happy_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Int;
type
TIntegerDynArray = TArray<Integer>;
{ TIntHelper }
if cache.Has(sum) then
exit(False);
n := sum;
cache.Add(sum);
until false;
end;
procedure TIntHelper.Next;
https://rosettacode.org/wiki/Happy_numbers 60/210
4/4/2021 Happy numbers - Rosetta Code
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.
Output:
1 7 10 13 19 23 28 31
DWScript (/wiki/Category:DWScript)
https://rosettacode.org/wiki/Happy_numbers 61/210
4/4/2021 Happy numbers - Rosetta Code
var n := 8;
var i : Integer;
Output:
1
7
10
13
19
23
28
31
https://rosettacode.org/wiki/Happy_numbers 62/210
4/4/2021 Happy numbers - Rosetta Code
Dyalect (/wiki/Category:Dyalect)
func happy(n) {
var m = []
while n > 1 {
m.add(n)
var x = n
n = 0
while x > 0 {
var d = x % 10
n += d * d
x /= 10
}
if m.indexOf(n) != -1 {
return false
}
}
return true
}
Output:
1 7 10 13 19 23 28 31
Déjà Vu (/wiki/Category:D%C3%A9j%C3%A0_Vu)
https://rosettacode.org/wiki/Happy_numbers 63/210
4/4/2021 Happy numbers - Rosetta Code
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
Output:
https://rosettacode.org/wiki/Happy_numbers 64/210
4/4/2021 Happy numbers - Rosetta Code
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
E (/wiki/Category:E)
This example does not show the output mentioned in the task description on this page (or a page linked to from here).
Please ensure that it meets all task requirements and remove this message.
Note that phrases in task descriptions such as "print and display" and "print and show" for example, indicate that (reasonable length) output be a
part of a language's solution.
https://rosettacode.org/wiki/Happy_numbers 65/210
4/4/2021 Happy numbers - Rosetta Code
Eiffel (/wiki/Category:Eiffel)
https://rosettacode.org/wiki/Happy_numbers 66/210
4/4/2021 Happy numbers - Rosetta Code
class
APPLICATION
create
make
make
-- Run application.
local
l_val: INTEGER (https://www.google.com/search?q=site%3Ahttps%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fdocs.eiffel.com%2Feiffelstudio%2Flibraries
do
from
l_val := 1
until
l_val > 100
loop
if is_happy_number (l_val) then
print (l_val.out)
print ("%N")
end
l_val := l_val + 1
end
end
https://rosettacode.org/wiki/Happy_numbers 67/210
4/4/2021 Happy numbers - Rosetta Code
l_set.put (l_number)
l_number := square_sum_of_digits (l_number)
end
Result := (l_number = 1)
end
feature{NONE (https://www.google.com/search?q=site%3Ahttps%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fdocs.eiffel.com%2Feiffelstudio%2Flibraries+none&btnI=I%27m+Feeling+L
end
Elena (/wiki/Category:Elena)
Translation of: C#
ELENA 4.x :
https://rosettacode.org/wiki/Happy_numbers 68/210
4/4/2021 Happy numbers - Rosetta Code
import extensions;
import system'collections;
import system'routines;
isHappy(int n)
{
auto cache := new List<int>(5);
int sum := 0;
int num := n;
while (num != 1)
{
if (cache.indexOfElement:num != -1)
{
^ false
};
cache.append(num);
while (num != 0)
{
int digit := num.mod:10;
sum += (digit*digit);
num /= 10
};
num := sum;
sum := 0
};
^ true
}
public program()
{
auto happynums := new List<int>(8);
int num := 1;
while (happynums.Length < 8)
{
if (isHappy(num))
{
happynums.append(num)
};
num += 1
};
https://rosettacode.org/wiki/Happy_numbers 69/210
4/4/2021 Happy numbers - Rosetta Code
Output:
Elixir (/wiki/Category:Elixir)
defmodule Happy do
def task(num) do
Process.put({:happy, 1}, true)
Stream.iterate(1, &(&1+1))
|> Stream.filter(fn n -> happy?(n) end)
|> Enum.take(num)
end
defp happy?(n) do
sum = square_sum(n, 0)
val = Process.get({:happy, sum})
if val == nil do
Process.put({:happy, sum}, false)
val = happy?(sum)
Process.put({:happy, sum}, val)
end
val
end
IO.inspect Happy.task(8)
Output:
https://rosettacode.org/wiki/Happy_numbers 70/210
4/4/2021 Happy numbers - Rosetta Code
Erlang (/wiki/Category:Erlang)
-module(tasks).
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
Command:
Output:
https://rosettacode.org/wiki/Happy_numbers 71/210
4/4/2021 Happy numbers - Rosetta Code
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):
-module(tasks).
-export([main/0]).
Output:
[1,7,10,13,19,23,28,31]
Euphoria (/wiki/Category:Euphoria)
https://rosettacode.org/wiki/Happy_numbers 72/210
4/4/2021 Happy numbers - Rosetta Code
function is_happy(integer n)
sequence seen
integer k
seen = {}
while n > 1 do
seen &= n
k = 0
while n > 0 do
k += power(remainder(n,10),2)
n = floor(n/10)
end while
n = k
if find(n,seen) then
return 0
end if
end while
return 1
end function
integer n,count
n = 1
count = 0
while count < 8 do
if is_happy(n) then
? n
count += 1
end if
n += 1
end while
Output:
1
7
10
13
19
23
28
31
https://rosettacode.org/wiki/Happy_numbers 73/210
4/4/2021 Happy numbers - Rosetta Code
F# (/wiki/Category:F_Sharp)
This requires the F# power pack to be referenced and the 2010 beta of F#
open System.Collections.Generic
open Microsoft.FSharp.Collections
let answer =
let sqr x = x*x // Classic square definition
let rec AddDigitSquare n =
match n with
| 0 -> 0 // Sum of squares for 0 is 0
| _ -> sqr(n % 10) + (AddDigitSquare (n / 10)) // otherwise add square of bottom digit to recursive call
let dict = new Dictionary<int, bool>() // Dictionary to memoize values
let IsHappy n =
if dict.ContainsKey(n) then // If we've already discovered it
dict.[n] // Return previously discovered value
else
let cycle = new HashSet<_>(HashIdentity (http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/namespace
let rec isHappyLoop n =
if cycle.Contains n then n = 1 // If there's a loop, return true if it's 1
else
cycle.Add n |> ignore // else add this value to the cycle
isHappyLoop (AddDigitSquare n) // and check the next number in the cycle
let f = isHappyLoop n // Keep track of whether we're happy or not
cycle |> Seq (http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/namespaces.html).iter (fun i -> dict
f // Return the boolean
1 // Starting with 1,
|> Seq (http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/namespaces.html).unfold (fun i -> Some (i, i + 1))
|> Seq (http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/namespaces.html).filter IsHappy
|> Seq (http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/namespaces.html).truncate 8
|> Seq (http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/namespaces.html).iter (Printf (http://research.mic
Output:
https://rosettacode.org/wiki/Happy_numbers 74/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
Factor (/wiki/Category:Factor)
USING: combinators kernel make math sequences ;
: squares ( n -- s )
0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;
: (happy?) ( n1 n2 -- ? )
[ squares ] [ squares squares ] bi* {
{ [ dup 1 = ] [ 2drop t ] }
{ [ 2dup = ] [ 2drop f ] }
[ (happy?) ]
} cond ;
: happy? ( n -- ? )
dup (happy?) ;
: happy-numbers ( n -- seq )
[
0 [ over 0 > ] [
dup happy? [ dup , [ 1 - ] dip ] when 1 +
] while 2drop
] { } make ;
Output:
8 happy-numbers ! { 1 7 10 13 19 23 28 31 }
FALSE (/wiki/Category:FALSE)
https://rosettacode.org/wiki/Happy_numbers 75/210
4/4/2021 Happy numbers - Rosetta Code
0 1
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%
Output:
Happy numbers: 1 7 10 13 19 23 28 31
Fantom (/wiki/Category:Fantom)
https://rosettacode.org/wiki/Happy_numbers 76/210
4/4/2021 Happy numbers - Rosetta Code
class Main
{
static Bool isHappy (Int n)
{
Int[] record := [,]
while (n != 1 && !record.contains(n))
{
record.add (n)
// find sum of squares of digits
newn := 0
while (n > 0)
{
newn += (n.mod(10) * n.mod(10))
n = n.div(10)
}
n = newn
}
return (n == 1)
}
Output:
https://rosettacode.org/wiki/Happy_numbers 77/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
FOCAL (/wiki/Category: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
Output:
https://rosettacode.org/wiki/Happy_numbers 78/210
4/4/2021 Happy numbers - Rosetta Code
= 1
= 7
= 10
= 13
= 19
= 23
= 28
= 31
Forth (/wiki/Category:Forth)
: next ( n -- n )
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
: cycle? ( n -- ? )
here dup @ cells +
begin dup here >
while 2dup @ = if 2drop true exit then
1 cells -
repeat
1 over +! dup @ cells + ! false ;
: happy? ( n -- ? )
0 here ! begin next dup cycle? until 1 = ;
: happy-numbers ( n -- )
0 swap 0 do
begin 1+ dup happy? until dup .
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.
https://rosettacode.org/wiki/Happy_numbers 79/210
4/4/2021 Happy numbers - Rosetta Code
CREATE HAPPINESS 0 C, 1 C, 0 C, 0 C, 0 C, 0 C, 0 C, 1 C, 0 C, 0 C,
: next ( n -- n')
0 swap BEGIN dup WHILE 10 /mod >r dup * + r> REPEAT drop ;
: happy? ( n -- t|f)
BEGIN dup 10 >= WHILE next REPEAT chars HAPPINESS + C@ 0<> ;
: happy-numbers ( n --) >r 0
BEGIN r@ WHILE
BEGIN 1+ dup happy? UNTIL dup . r> 1- >r
REPEAT r> drop drop ;
8 happy-numbers
Output:
1 7 10 13 19 23 28 31
in about 9 seconds.
Fortran (/wiki/Category:Fortran)
https://rosettacode.org/wiki/Happy_numbers 80/210
4/4/2021 Happy numbers - Rosetta Code
program happy
implicit none
integer, parameter :: find = 8
integer :: found
integer :: number
found = 0
number = 1
do
if (found == find) then
exit
end if
if (is_happy (number)) then
found = found + 1
write (*, '(i0)') number
end if
number = number + 1
end do
contains
implicit none
integer, intent (in) :: number
integer :: result
integer :: digit
integer :: rest
integer :: work
result = 0
work = number
do
if (work == 0) then
exit
end if
rest = work / 10
digit = work - 10 * rest
result = result + digit * digit
work = rest
end do
https://rosettacode.org/wiki/Happy_numbers 81/210
4/4/2021 Happy numbers - Rosetta Code
implicit none
integer, intent (in) :: number
logical :: result
integer :: turtoise
integer :: hare
turtoise = number
hare = number
do
turtoise = sum_digits_squared (turtoise)
hare = sum_digits_squared (sum_digits_squared (hare))
if (turtoise == hare) then
exit
end if
end do
result = turtoise == 1
Output:
1
7
10
13
19
23
28
31
FreeBASIC (/wiki/Category:FreeBASIC)
https://rosettacode.org/wiki/Happy_numbers 82/210
4/4/2021 Happy numbers - Rosetta Code
https://rosettacode.org/wiki/Happy_numbers 83/210
4/4/2021 Happy numbers - Rosetta Code
Output:
1 => 1
2 => 7
3 => 10
4 => 13
5 => 19
6 => 23
7 => 28
8 => 31
Frege (/wiki/Category:Frege)
Translation of: Haskell
Works with: Frege (/wiki/Frege) version 3.21.586-g026e8d7
import Prelude.Math
-- ugh, since Frege doesn't have Set, use Map instead
import Data.Map (member, insertMin, empty emptyMap)
main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n
Output:
1 7 10 13 19 23 28 31
runtime 0.614 wallclock seconds.
https://rosettacode.org/wiki/Happy_numbers 84/210
4/4/2021 Happy numbers - Rosetta Code
Fōrmulæ (/wiki/Category:F%C5%8Drmul%C3%A6)
In this (https://wiki.formulae.org/Happy_numbers) page you can see the solution of this task.
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text (more info
(http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions)). Moreover, there can be multiple visual representations of the same program. Even
though it is possible to have textual representation —i.e. XML, JSON— they are intended for transportation effects more than visualization and edition.
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
Go (/wiki/Category:Go)
package main
import "fmt"
func main() {
for found, n := 0, 1; found < 8; n++ {
if happy(n) {
fmt.Print(n, " ")
found++
}
}
fmt.Println()
}
https://rosettacode.org/wiki/Happy_numbers 85/210
4/4/2021 Happy numbers - Rosetta Code
Output:
1 7 10 13 19 23 28 31
Groovy (/wiki/Category:Groovy)
Number (https://www.google.de/search?as_q=Number&num=100&hl=en&as_occt=url&as_sitesearch=java.sun.com%2Fj2se%2F1%2E5%2E0%2Fdocs%2Fapi%
def (https://www.google.de/search?q=site%3Agroovy.codehaus.org/%20def) number = delegate as (https://www.google.de/search?q=site%3
def (https://www.google.de/search?q=site%3Agroovy.codehaus.org/%20def) cycle = new (https://www.google.de/search?q=site%3Agroovy.c
while (https://www.google.de/search?q=site%3Agroovy.codehaus.org/%20while) (number != 1 && !cycle.contains (https://www.google.de/
cycle << number
number = (number as (https://www.google.de/search?q=site%3Agroovy.codehaus.org/%20as) String (https://www.google.de/search?as_
}
number == 1
}
Output:
Harbour (/wiki/Category:Harbour)
https://rosettacode.org/wiki/Happy_numbers 86/210
4/4/2021 Happy numbers - Rosetta Code
PROCEDURE Main()
LOCAL i := 8, nH := 0
WHILE i > 0
IF IsHappy( ++nH )
?? hb_NtoS( nH ) + " "
--i
ENDIF
END
RETURN
IF nSum == 1
aUnhappy := {}
RETURN .T.
ELSEIF AScan( aUnhappy, nSum ) > 0
RETURN .F.
ENDIF
Output:
Haskell (/wiki/Category:Haskell)
https://rosettacode.org/wiki/Happy_numbers 87/210
4/4/2021 Happy numbers - Rosetta Code
main :: IO (https://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO) ()
main = mapM_ (https://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:mapM_) print (https://haskell.org/ghc/docs/latest
Output:
1
7
10
13
19
23
28
31
We can create a cache for small numbers to greatly speed up the process:
https://rosettacode.org/wiki/Happy_numbers 88/210
4/4/2021 Happy numbers - Rosetta Code
main :: IO (https://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO) ()
main = print (https://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print) $ sum (https://haskell.org/ghc/docs/latest
Output:
327604323
https://rosettacode.org/wiki/Happy_numbers 89/210
4/4/2021 Happy numbers - Rosetta Code
procedure main(arglist)
local n
n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8
writes("The first ",n," happy numbers are:")
every writes(" ", happy(seq()) \ n )
write()
end
| happynum.exe
J (/wiki/Category:J)
8{. (#~1=+/@(*:@(,.&.":))^:(1&~:*.4&~:)^:_ "0) 1+i.100
1 7 10 13 19 23 28 31
f ^: cond ^: _ input
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.
https://rosettacode.org/wiki/Happy_numbers 90/210
4/4/2021 Happy numbers - Rosetta Code
Java (/wiki/Category:Java)
Works with: Java (/wiki/Java) version 1.5+
Translation of: JavaScript
https://rosettacode.org/wiki/Happy_numbers 91/210
4/4/2021 Happy numbers - Rosetta Code
import java.util.HashSet;
public class Happy{
public static boolean happy(long number){
long m = 0;
int digit = 0;
HashSet (http://java.sun.com/j2se/1%2E5%2E0/docs/api/java/util/HashSet.html)<Long (http://java.sun.com/j2se/1%2E5%2E0/docs/api/
while(number != 1 && cycle.add(number)){
m = 0;
while(number > 0){
digit = (int)(number % 10);
m += digit*digit;
number /= 10;
}
number = m;
}
return number == 1;
}
Output:
1
7
10
13
19
23
28
31
https://rosettacode.org/wiki/Happy_numbers 92/210
4/4/2021 Happy numbers - Rosetta Code
Java 1.8
Works with: Java (/wiki/Java) version 1.8
Translation of: Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
Output:
https://rosettacode.org/wiki/Happy_numbers 93/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
JavaScript (/wiki/Category:JavaScript)
ES5
Iteration
https://rosettacode.org/wiki/Happy_numbers 94/210
4/4/2021 Happy numbers - Rosetta Code
function happy(number) {
var m, digit ;
var cycle = [] ;
var cnt = 8 ;
var number = 1 ;
while(cnt-- > 0) {
while(!happy(number))
number++ ;
document.write(number + " ") ;
number++ ;
}
Output:
1 7 10 13 19 23 28 31
ES6
Functional composition
Translation of: Haskell
https://rosettacode.org/wiki/Happy_numbers 95/210
4/4/2021 Happy numbers - Rosetta Code
(() => {
https://rosettacode.org/wiki/Happy_numbers 96/210
4/4/2021 Happy numbers - Rosetta Code
// TEST -------------------------------------------------------------------
return show(
take(8, filter(isHappy, enumFromTo(1, 50)))
);
})()
Output:
Or, to stop immediately at the 8th member of the series, we can preserve functional composition while using an iteratively implemented until() function:
https://rosettacode.org/wiki/Happy_numbers 97/210
4/4/2021 Happy numbers - Rosetta Code
(() => {
https://rosettacode.org/wiki/Happy_numbers 98/210
4/4/2021 Happy numbers - Rosetta Code
// TEST -------------------------------------------------------------------
return show(
until(
m => m.xs.length === 8,
m => {
const n = m.n;
return {
n: n + 1,
xs: isHappy(n) ? m.xs.concat(n) : m.xs
};
}, {
n: 1,
xs: []
}
)
.xs
);
})();
Output:
jq (/wiki/Category:Jq)
Works with: jq (/wiki/Jq) version 1.4
https://rosettacode.org/wiki/Happy_numbers 99/210
4/4/2021 Happy numbers - Rosetta Code
def is_happy_number:
def next: tostring | explode | map( (. - 48) | .*.) | add;
def last(g): reduce g as $i (null; $i);
# state: either 1 or [i, o]
# where o is an an object with the previously encountered numbers as keys
def loop:
recurse( if . == 1 then empty # all done
elif .[0] == 1 then 1 # emit 1
else (.[0]| next) as $n
| if $n == 1 then 1
elif .[1]|has($n|tostring) then empty
else [$n, (.[1] + {($n|tostring):true}) ]
end
end );
1 == last( [.,{}] | loop );
happy($n|tonumber)
Output:
https://rosettacode.org/wiki/Happy_numbers 100/210
4/4/2021 Happy numbers - Rosetta Code
$ jq --arg n 8 -n -f happy.jq
1
7
10
13
19
23
28
31
Julia (/wiki/Category:Julia)
function happy(x)
happy_ints = ref(Int)
int_try = 1
while length(happy_ints) < x
n = int_try
past = ref(Int)
while n != 1
n = sum([y^2 for y in digits(n)])
contains(past,n) ? break : push!(past,n)
end
n == 1 && push!(happy_ints,int_try)
int_try += 1
end
return happy_ints
end
Output
https://rosettacode.org/wiki/Happy_numbers 101/210
4/4/2021 Happy numbers - Rosetta Code
julia> happy(8)
8-element Int32 Array:
1
7
10
13
19
23
28
31
A recursive version:
Output:
julia> show(happy(8))
[1,7,10,13,19,23,28,31,32]
Alternate, Translation of C
Faster with use of cache
Translation of: C
https://rosettacode.org/wiki/Happy_numbers 102/210
4/4/2021 Happy numbers - Rosetta Code
K (/wiki/Category:K)
hpy: {x@&1={~|/x=1 4}{_+/_sqr 0$'$x}//:x}
hpy 1+!100
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
8#hpy 1+!100
1 7 10 13 19 23 28 31
https://rosettacode.org/wiki/Happy_numbers 103/210
4/4/2021 Happy numbers - Rosetta Code
/ happynum.k
Output:
\l happynum
hnum 8
List of 8 Happy Numbers
1 7 10 13 19 23 28 31
Kotlin (/wiki/Category:Kotlin)
Translation of: C#
https://rosettacode.org/wiki/Happy_numbers 104/210
4/4/2021 Happy numbers - Rosetta Code
// version 1.0.5-2
Output:
Lasso (/wiki/Category:Lasso)
https://rosettacode.org/wiki/Happy_numbers 105/210
4/4/2021 Happy numbers - Rosetta Code
#!/usr/bin/lasso9
Output:
https://rosettacode.org/wiki/Happy_numbers 106/210
4/4/2021 Happy numbers - Rosetta Code
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
Output:-
1 1
2 7
3 10
4 13
5 19
6 23
7 28
8 31
(/wiki/File:Happy_Numbers,_Locomotive_BASIC.png)
Logo (/wiki/Category:Logo)
https://rosettacode.org/wiki/Happy_numbers 108/210
4/4/2021 Happy numbers - Rosetta Code
to sum_of_square_digits :number
output (apply "sum (map [[d] d*d] ` :number))
end
print n_happy 8
bye
Output:
1 7 10 13 19 23 28 31
LOLCODE (/wiki/Category:LOLCODE)
Works with: lci 0.10.3 (/mw/index.php?title=Lci_0.10.3&action=edit&redlink=1)
https://rosettacode.org/wiki/Happy_numbers 109/210
4/4/2021 Happy numbers - Rosetta Code
OBTW
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
TLDR
HAI 1.3
CAN HAS STDIO?
https://rosettacode.org/wiki/Happy_numbers 110/210
4/4/2021 Happy numbers - Rosetta Code
GTFO
OIC
I HAS A DIGIT ITZ MOD OF NUM AN 10
NUM R QUOSHUNT OF NUM AN 10
I HAS A SQUARE ITZ PRODUKT OF DIGIT AN DIGIT
NEXT R SUM OF NEXT AN SQUARE
IM OUTTA YR LOOP
FOUND YR NEXT
IF U SAY SO
Output:
https://rosettacode.org/wiki/Happy_numbers 111/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
Lua (/wiki/Category:Lua)
function digits(n)
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
function sumsq(a, ...)
return a and a ^ 2 + sumsq(...) or 0
end
local happy = setmetatable({true, false, false, false}, {
__index = function(self, n)
self[n] = self[sumsq(digits(n))]
return self[n]
end } )
i, j = 0, 1
repeat
i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8
Output:
1
7
10
13
19
23
28
31
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
k$=str$(abs(n),"")
Sum=0
For i=1 to len(k$)
sum+=val(mid$(k$,i,1))**2
Next i
=sum
}
IsHappy=Lambda sumOfSquares (n) ->{
Inventory sequence
While n<>1 {
Append sequence, n
n=sumOfSquares(n)
if exist(sequence, n) then =false : Break
}
=True
}
=Lambda IsHappy ->{
numleft=8
numToTest=1
While numleft {
if ishappy(numToTest) Then {
Print numToTest
numleft--
}
numToTest++
}
}
}
PrintHappy=factoryHappy()
Call PrintHappy()
Output:
https://rosettacode.org/wiki/Happy_numbers 113/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
MAD (/wiki/Category:MAD)
NORMAL MODE IS INTEGER
BOOLEAN CYCLE
DIMENSION CYCLE(200)
VECTOR VALUES OUTFMT = $I2*$
SEEN = 0
I = 0
END OF PROGRAM
https://rosettacode.org/wiki/Happy_numbers 114/210
4/4/2021 Happy numbers - Rosetta Code
Output:
1
7
10
13
19
23
28
31
Maple (/wiki/Category: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.)
(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,
https://rosettacode.org/wiki/Happy_numbers 115/210
4/4/2021 Happy numbers - Rosetta Code
> n := 1234567890987654321:
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
570
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).
Happy? := proc( n )
if n = 1 then
true
elif n = 4 then
false
else
local s := SumSqDigits( n );
while not ( s in { 1, 4 } ) do
s := SumSqDigits( s )
end do;
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.
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.
https://rosettacode.org/wiki/Happy_numbers 116/210
4/4/2021 Happy numbers - Rosetta Code
FindHappiness := proc( N )
local count := 0;
local T := table();
for local i while count < N do
if Happy?( i ) then
count := 1 + count;
T[ count ] := i
end if
end do;
{seq}( T[ i ], i = 1 .. count )
end proc:
> FindHappiness( 8 );
{1, 7, 10, 13, 19, 23, 28, 31}
For completeness, here is an implementation of the cycle detection algorithm for recognizing happy numbers. It is much slower, however.
https://rosettacode.org/wiki/Happy_numbers 117/210
4/4/2021 Happy numbers - Rosetta Code
AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]]
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1
HappyQ[1337]
HappyQ[137]
gives back:
True
False
m = 8;
n = 1;
i = 0;
happynumbers = {};
While[n <= m,
i++;
If[HappyQ[i],
n++;
AppendTo[happynumbers, i]
]
]
happynumbers
gives back:
MATLAB (/wiki/Category:MATLAB)
Recursive version:
https://rosettacode.org/wiki/Happy_numbers 118/210
4/4/2021 Happy numbers - Rosetta Code
function findHappyNumbers
nHappy = 0;
k = 1;
while nHappy < 8
if isHappyNumber(k, [])
fprintf (https://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html)('%d ', k)
nHappy = nHappy+1;
end
k = k+1;
end
fprintf (https://www.mathworks.com/access/helpdesk/help/techdoc/ref/fprintf.html)('\n')
end
Output:
1 7 10 13 19 23 28 31
MAXScript (/wiki/Category:MAXScript)
https://rosettacode.org/wiki/Happy_numbers 119/210
4/4/2021 Happy numbers - Rosetta Code
fn isHappyNumber n =
(
local pastNumbers = #()
while n != 1 do
(
n = n as string
local newNumber = 0
for i = 1 to n.count do
(
local digit = n[i] as integer
newNumber += pow digit 2
)
n = newNumber
if (finditem pastNumbers n) != 0 do return false
append pastNumbers newNumber
)
n == 1
)
printed = 0
for i in (for h in 1 to 500 where isHappyNumber h collect h) do
(
if printed == 8 do exit
print i as string
printed += 1
Output:
1
7
10
13
19
23
28
31
https://rosettacode.org/wiki/Happy_numbers 120/210
4/4/2021 Happy numbers - Rosetta Code
Mercury (/wiki/Category:Mercury)
:- module happy.
:- interface.
:- import_module io.
:- implementation.
:- import_module int, list, set_tree234.
main(!IO) :-
print_line(get_n_happy_numbers(8, 1), !IO).
get_n_happy_numbers(NumToFind, N) =
( if NumToFind > 0 then
( if is_happy(N, init)
then [N | get_n_happy_numbers(NumToFind - 1, N + 1)]
else get_n_happy_numbers(NumToFind, N + 1)
)
else
[]
).
is_happy(1, _).
is_happy(N, !.Seen) :-
not member(N, !.Seen),
insert(N, !Seen),
is_happy(sum_sqr_digits(N), !.Seen).
sum_sqr_digits(N) =
( if N < 10 then sqr(N) else sqr(N mod 10) + sum_sqr_digits(N div 10) ).
sqr(X) = X * X.
https://rosettacode.org/wiki/Happy_numbers 121/210
4/4/2021 Happy numbers - Rosetta Code
Output:
MiniScript (/wiki/Category: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.
isHappy = function(x)
while true
if x == 89 then return false
sum = 0
while x > 0
sum = sum + (x % 10)^2
x = floor(x / 10)
end while
if sum == 1 then return true
x = sum
end while
end function
found = []
i = 1
while found.len < 8
if isHappy(i) then found.push i
i = i + 1
end while
print "First 8 happy numbers: " + found
Output:
First 8 happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]
ML (/wiki/Category:ML)
mLite (/wiki/Category:MLite)
https://rosettacode.org/wiki/Happy_numbers 122/210
4/4/2021 Happy numbers - Rosetta Code
(*
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
stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends
in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your
output here.
*)
local
fun get_digits
(d, s) where (d = 0) = s
| (d, s) = get_digits( d div 10, (d mod 10) :: s)
| n = get_digits( n div 10, [n mod 10] )
;
fun mem
(x, []) = false
| (x, a :: as) where (x = a) = true
| (x, _ :: as) = mem (x, as)
in
fun happy
1 = "happy"
| n =
let
val this = (fold (+,0) ` map (fn n = n ^ 2) ` get_digits n);
val sads = [2, 4, 16, 37, 58, 89, 145, 42, 20]
in
if (mem (n,sads)) then
"unhappy"
else
happy this
end
end
;
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
Output:
https://rosettacode.org/wiki/Happy_numbers 123/210
4/4/2021 Happy numbers - Rosetta Code
1 is happy
2 is unhappy
3 is unhappy
4 is unhappy
5 is unhappy
6 is unhappy
7 is happy
8 is unhappy
9 is unhappy
10 is happy
MUMPS (/wiki/Category:MUMPS)
ISHAPPY(N)
;Determines if a number N is a happy number
;Note that the returned strings do not have a leading digit unless it is a happy number
IF (N'=N\1)!(N<0) QUIT "Not a positive integer"
NEW SUM,I
;SUM is the sum of the square of each digit
;I is a loop variable
;SEQ is the sequence of previously checked SUMs from the original N
;If it isn't set already, initialize it to an empty string
IF $DATA(SEQ)=0 NEW SEQ SET SEQ=""
SET SUM=0
FOR I=1:1:$LENGTH(N) DO
.SET SUM=SUM+($EXTRACT(N,I)*$EXTRACT(N,I))
QUIT:(SUM=1) SUM
QUIT:$FIND(SEQ,SUM)>1 "Part of a sequence not containing 1"
SET SEQ=SEQ_","_SUM
QUIT $$ISHAPPY(SUM)
HAPPY(C) ;Finds the first C happy numbers
NEW I
;I is a counter for what integer we're looking at
WRITE !,"The first "_C_" happy numbers are:"
FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
KILL I
QUIT
Output:
https://rosettacode.org/wiki/Happy_numbers 124/210
4/4/2021 Happy numbers - Rosetta Code
USER>D HAPPY^ROSETTA(8)
USER>
NetRexx (/wiki/Category:NetRexx)
Translation of: REXX
https://rosettacode.org/wiki/Happy_numbers 125/210
4/4/2021 Happy numbers - Rosetta Code
/*NetRexx program to display the 1st 8 (or specified arg) happy numbers*/
limit = arg[0] /*get argument for LIMIT. */
say limit
if limit = null, limit ='' then limit=8 /*if not specified, set LIMIT to 8*/
haps = 0 /*count of happy numbers so far. */
loop n=1 while haps < limit /*search integers starting at one.*/
q=n /*Q may or may not be "happy". */
a=0
Output
1
7
10
13
19
23
28
31
https://rosettacode.org/wiki/Happy_numbers 126/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
32
Nim (/wiki/Category:Nim)
Translation of: Python
import intsets
for x in 0..31:
if happy(x):
echo x
Output:
https://rosettacode.org/wiki/Happy_numbers 127/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
Objeck (/wiki/Category:Objeck)
https://rosettacode.org/wiki/Happy_numbers 128/210
4/4/2021 Happy numbers - Rosetta Code
use IO;
use Structure;
bundle Default {
class HappyNumbers {
function : native : IsHappy(n : Int) ~ Bool {
cache := IntVector->New();
sum := 0;
while(n <> 1) {
if(cache->Has(n)) {
return false;
};
cache->AddBack(n);
while(n <> 0) {
digit := n % 10;
sum += (digit * digit);
n /= 10;
};
n := sum;
sum := 0;
};
return true;
}
while(happynums->Size() < 8) {
if(IsHappy(num)) {
happynums->AddBack(num);
};
num += 1;
};
https://rosettacode.org/wiki/Happy_numbers 129/210
4/4/2021 Happy numbers - Rosetta Code
Console->PrintLine("");
}
}
}
output:
OCaml (/wiki/Category:OCaml)
Using Floyd's cycle-finding algorithm (https://en.wikipedia.org/wiki/Cycle_detection).
let step =
let rec aux s n =
if n =/ Int 0 then s else
let q = quo_num n (Int 10)
and r = mod_num n (Int 10)
in aux (s +/ (r */ r)) q
in aux (Int 0) ;;
let happy n =
let rec aux x y =
if x =/ y then x else aux (step x) (step (step y))
in (aux n (step n)) =/ Int 1 ;;
let first n =
let rec aux v x n =
if n = 0 then v else
if happy x
then aux (x::v) (x +/ Int 1) (n - 1)
else aux v (x +/ Int 1) n
in aux [ ] (Int 1) n ;;
Output:
https://rosettacode.org/wiki/Happy_numbers 130/210
4/4/2021 Happy numbers - Rosetta Code
Oforth (/wiki/Category:Oforth)
: isHappy(n)
| cycle |
ListBuffer new ->cycle
while(n 1 <>) [
cycle include(n) ifTrue: [ false return ]
cycle add(n)
0 n asString apply(#[ asDigit sq + ]) ->n
]
true ;
: happyNum(N)
| numbers |
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;
Output:
>happyNum(8)
[1, 7, 10, 13, 19, 23, 28, 31]
ooRexx (/wiki/Category:OoRexx)
https://rosettacode.org/wiki/Happy_numbers 131/210
4/4/2021 Happy numbers - Rosetta Code
count = 0
say "First 8 happy numbers are:"
loop i = 1 while count < 8
if happyNumber(i) then do
count += 1
say i
end
end
::routine happyNumber
use strict arg number
https://rosettacode.org/wiki/Happy_numbers 132/210
4/4/2021 Happy numbers - Rosetta Code
Oz (/wiki/Category:Oz)
https://rosettacode.org/wiki/Happy_numbers 133/210
4/4/2021 Happy numbers - Rosetta Code
functor
import
System
define
fun {IsHappy N}
{IsHappy2 N nil}
end
fun {Digits N}
{Map {Int.toString N} fun {$ D} D - &0 end}
end
https://rosettacode.org/wiki/Happy_numbers 134/210
4/4/2021 Happy numbers - Rosetta Code
Output:
[1 7 10 13 19 23 28 31]
PARI/GP (/wiki/Category:PARI/GP)
Works with: PARI/GP (/wiki/PARI/GP) version 2.4.3 and above
This code uses the select (http://pari.math.u-bordeaux.fr/dochtml/html/Programming_in_GP:_other_specific_functions.html#select)() function, which was
added in PARI version 2.4.2. The order of the arguments changed between versions; to use in 2.4.2 change select(function, vector) to
select(vector, function) .
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.
H=[1,7,10,13,19,23,28,31,32,44,49,68,70,79,82,86,91,94,97,100,103,109,129,130,133,139,167,176,188,190,192,193,203,208,219,226,230,236,
isHappy(n)={
if(n<262,
setsearch(H,n)>0
,
n=eval(Vec(Str(n)));
isHappy(sum(i=1,#n,n[i]^2))
)
};
select(isHappy, vector(31,i,i))
Output:
Pascal (/wiki/Category:Pascal)
https://rosettacode.org/wiki/Happy_numbers 135/210
4/4/2021 Happy numbers - Rosetta Code
uses
Math;
https://rosettacode.org/wiki/Happy_numbers 136/210
4/4/2021 Happy numbers - Rosetta Code
var
n, count: integer;
begin
n := 1;
count := 0;
while count < 8 do
begin
if is_happy(n) then
begin
inc(count);
write(n, ' ');
end;
inc(n);
end;
writeln;
end.
Output:
:> ./HappyNumbers
1 7 10 13 19 23 28 31
https://rosettacode.org/wiki/Happy_numbers 137/210
4/4/2021 Happy numbers - Rosetta Code
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
tSumSqrDgts = array[0..cDigit2] of word;
tCache = array[0..2*HighCache] of word;
tSqrdSumCache = array[0..2*HighCache] of Uint32;
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
https://rosettacode.org/wiki/Happy_numbers 138/210
4/4/2021 Happy numbers - Rosetta Code
var
i,j,n,sq,Base1: NativeInt;
begin
For i := 0 to Base-1 do
SumSqrDgts[i] := i*i;
Base1 := Base;
n := 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;
procedure CalcSqrdSumCache1;
var
Count : tSqrdSumCache;
i,sq,result : NativeInt;
begin
For i :=High(Count) downto 0 do
Count[i] := 0;
https://rosettacode.org/wiki/Happy_numbers 139/210
4/4/2021 Happy numbers - Rosetta Code
procedure CalcSqrdSumCache2;
var
Count : tSqrdSumCache;
i,sq,result : NativeInt;
begin
For i :=High(Count) downto 0 do
Count[i] := 0;
For i := cDigit2-1 downto 0 do
inc(count[SumSqrDgts[i]]);
For i := High(Count) downto 0 do
if count[i] <> 0 then
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;
var
https://rosettacode.org/wiki/Happy_numbers 140/210
4/4/2021 Happy numbers - Rosetta Code
n,s,p : NativeUint;
Begin
fillchar(SqrdSumCache1,SizeOf(SqrdSumCache1),#0);
fillchar(SqrdSumCache2,SizeOf(SqrdSumCache2),#0);
InitSumSqrDgts;
fillChar(Cache,SizeOf(Cache),#0);
Cache[1] := 1;
For n := 1 to High(Cache) do
Begin
If Cache[n] = 0 then
Begin
//start a linked list
Cache[n] := n;
p := n;
s := SumSqrdDgt(p);
while Cache[s] = 0 do
Begin
Cache[s] := p;
p := s;
s := SumSqrdDgt(p);
end;
//mark linked list backwards as happy number
IF Cache[s] = 1 then
Begin
repeat
s := Cache[p];
Cache[p] := 1;
p := s;
until s = n;
Cache[n] := 1;
end;
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;
https://rosettacode.org/wiki/Happy_numbers 141/210
4/4/2021 Happy numbers - Rosetta Code
is_happy := Boolean(Cache[SumSqrdDgt(n)])
end;
var
n, count :Uint64;
Limit: NativeUint;
begin
write('cDigit1 = ',Numb2USA(IntToStr(cDigit1)));
https://rosettacode.org/wiki/Happy_numbers 142/210
4/4/2021 Happy numbers - Rosetta Code
T0 := now;
T1 := T0;
n := 1;
Limit := 10;
repeat
writeln('1E',n:2,' n.th happy number ',Numb2USA(IntToStr(nthHappy(Limit))):26,
FormatDateTime(' HH:NN:SS.ZZZ',now-T1));
T1 := now;
inc(n);
Limit := limit*10;
until n> cMaxPot;
writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0));
end.
output
https://rosettacode.org/wiki/Happy_numbers 143/210
4/4/2021 Happy numbers - Rosetta Code
real 0m0,685s
https://rosettacode.org/wiki/Happy_numbers 144/210
4/4/2021 Happy numbers - Rosetta Code
real 0m10,627s
Perl (/wiki/Category: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 {
my $s = shift (https://perldoc.perl.org/functions/shift.html);
while ($s > 6 && $s != 89) {
$s = sum(map (https://perldoc.perl.org/functions/map.html) { $_*$_ } split (https://perldoc.perl.org/functions/split.html)(//,$s))
}
$s == 1;
}
my $n = 0;
print (https://perldoc.perl.org/functions/print.html) join (https://perldoc.perl.org/functions/join.html)(" ", map (https://perldoc.pe
Output:
1 7 10 13 19 23 28 31
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.
https://rosettacode.org/wiki/Happy_numbers 145/210
4/4/2021 Happy numbers - Rosetta Code
my $n;
is_happy( ++$n ) and print (https://perldoc.perl.org/functions/print.html) "$n " or redo for 1..8;
Output:
1 7 10 13 19 23 28 31
Phix (/wiki/Category:Phix)
Copy of Euphoria (/wiki/Happy_numbers#Euphoria) tweaked to give a one-line output
https://rosettacode.org/wiki/Happy_numbers 146/210
4/4/2021 Happy numbers - Rosetta Code
function is_happy(integer n)
sequence seen = {}
integer k
while n>1 do
seen &= n
k = 0
while n>0 do
k += power(remainder(n,10),2)
n = floor(n/10)
end while
n = k
if find(n,seen) then
return 0
end if
end while
return 1
end function
integer n = 1
sequence s = {}
while length(s)<8 do
if is_happy(n) then
s &= n
end if
n += 1
end while
?s
Output:
{1,7,10,13,19,23,28,31}
PHP (/wiki/Category:PHP)
Translation of: D
https://rosettacode.org/wiki/Happy_numbers 147/210
4/4/2021 Happy numbers - Rosetta Code
function isHappy($n) {
while (1) {
$total = 0;
while ($n > 0) {
$total += pow (http://www.php.net/pow)(($n % 10), 2);
$n /= 10;
}
if ($total == 1)
return true;
if (array_key_exists (http://www.php.net/array_key_exists)($total, $past))
return false;
$n = $total;
$past[$total] = 0;
}
}
$i = $cnt = 0;
while ($cnt < 8) {
if (isHappy($i)) {
echo "$i ";
$cnt++;
}
$i++;
}
1 7 10 13 19 23 28 31
PicoLisp (/wiki/Category:PicoLisp)
https://rosettacode.org/wiki/Happy_numbers 148/210
4/4/2021 Happy numbers - Rosetta Code
(let H 0
(do 8
(until (happy? (inc 'H)))
(printsp H) ) )
Output:
1 7 10 13 19 23 28 31
PL/I (/wiki/Category:PL/I)
https://rosettacode.org/wiki/Happy_numbers 149/210
4/4/2021 Happy numbers - Rosetta Code
main_loop:
do j = 1 to 100;
n = j;
do i = 1 to 100;
m = 0;
/* Form the sum of squares of the digits. */
do until (n = 0);
m = m + mod(n, 10)**2;
n = n/10;
end;
if m = 1 then
do;
put skip list (j || ' is a happy number');
nh = nh + 1;
if nh = 8 then return;
iterate main_loop;
end;
n = m; /* Replace n with the new number formed from digits. */
end;
end;
end test;
OUTPUT:
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
Potion (/wiki/Category:Potion)
https://rosettacode.org/wiki/Happy_numbers 150/210
4/4/2021 Happy numbers - Rosetta Code
sqr = (n): n * n.
isHappy = (n) :
loop :
if (n == 1): return true.
if (n == 4): return false.
sum = 0
n = n string
n length times (i): sum = sum + sqr(n(i) number integer).
n = sum
.
.
firstEight = ()
i = 0
while (firstEight length < 8) :
i++
if (isHappy(i)): firstEight append(i).
.
firstEight string print
PowerShell (/wiki/Category:PowerShell)
https://rosettacode.org/wiki/Happy_numbers 151/210
4/4/2021 Happy numbers - Rosetta Code
Output :
happy(8)
7,10,13,19,23,28,31,32
Prolog (/wiki/Category:Prolog)
Works with: SWI-Prolog (/wiki/SWI-Prolog)
https://rosettacode.org/wiki/Happy_numbers 152/210
4/4/2021 Happy numbers - Rosetta Code
happy_numbers(L, Nb) :-
% creation of the list
length(L, Nb),
% Process of this list
get_happy_number(L, 1).
get_list_digits(N, LD) :-
number_chars (http://pauillac.inria.fr/~deransar/prolog/bips.html)(N, LCD),
maplist(number_chars_, LD, LCD).
number_chars_(D, CD) :-
https://rosettacode.org/wiki/Happy_numbers 153/210
4/4/2021 Happy numbers - Rosetta Code
square(N, SN) :-
SN is (http://pauillac.inria.fr/~deransar/prolog/bips.html) N * N.
Output :
?- happy_numbers(L, 8).
L = [1,7,10,13,19,23,28,31].
PureBasic (/wiki/Category:PureBasic)
https://rosettacode.org/wiki/Happy_numbers 154/210
4/4/2021 Happy numbers - Rosetta Code
#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
Sample output:
https://rosettacode.org/wiki/Happy_numbers 155/210
4/4/2021 Happy numbers - Rosetta Code
#1 1
#2 7
#3 10
#4 13
#5 19
#6 23
#7 28
#8 31
Python (/wiki/Category:Python)
Procedural
>>> def happy(n):
past = set()
while n != 1:
n = sum(int(i)**2 for i in str(n))
if n in past:
return False
past.add(n)
return True
https://rosettacode.org/wiki/Happy_numbers 156/210
4/4/2021 Happy numbers - Rosetta Code
'''Happy numbers'''
# main :: IO ()
def main():
'''Test'''
print(
take(8)(
happyNumbers()
)
)
return 1 == until(p)(f)(n)
https://rosettacode.org/wiki/Happy_numbers 157/210
4/4/2021 Happy numbers - Rosetta Code
# GENERIC -------------------------------------------------
if __name__ == '__main__':
main()
Output:
Quackery (/wiki/Category:Quackery)
https://rosettacode.org/wiki/Happy_numbers 158/210
4/4/2021 Happy numbers - Rosetta Code
[ 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
Output:
[ 1 7 10 13 19 23 28 31 ]
R (/wiki/Category:R)
https://rosettacode.org/wiki/Happy_numbers 159/210
4/4/2021 Happy numbers - Rosetta Code
Example usage
is.happy(2)
[1] FALSE
attr(,"cycle")
[1] 4 16 37 58 89 145 42 20
https://rosettacode.org/wiki/Happy_numbers 160/210
4/4/2021 Happy numbers - Rosetta Code
1 7 10 13 19 23 28 31 32 44 49
1 7 10 13 19 23 28 31
Racket (/wiki/Category:Racket)
https://rosettacode.org/wiki/Happy_numbers 161/210
4/4/2021 Happy numbers - Rosetta Code
#lang racket
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
result
(sum-of-squared-digits (quotient number 10)
(+ result (expt (remainder number 10) 2)))))
Raku (/wiki/Category:Raku)
(formerly Perl 6)
Output:
https://rosettacode.org/wiki/Happy_numbers 162/210
4/4/2021 Happy numbers - Rosetta Code
1 7 10 13 19 23 28 31
Here's another approach that uses a different set of tricks including lazy lists, gather/take, repeat-until, and the cross metaoperator X.
say ~@happy[^8];
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):
Again, output is the same as above. It is not clear whether this version returns in finite time for any integer, though.
Relation (/wiki/Category:Relation)
https://rosettacode.org/wiki/Happy_numbers 163/210
4/4/2021 Happy numbers - Rosetta Code
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
https://rosettacode.org/wiki/Happy_numbers 164/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
REXX (/wiki/Category:REXX)
unoptimized
/*REXX program computes and displays a specified amount of happy numbers. */
parse arg limit . /*obtain optional argument from the CL.*/
if limit=='' | limit=="," then limit=8 /*Not specified? Then use the default.*/
haps=0 /*count of the happy numbers (so far).*/
do n=1 while haps<limit; @.=0; q=n /*search the integers starting at unity*/
do until q==1 /*determine if Q is a happy number.*/
s=0 /*prepare to add squares of digits. */
do j=1 for length(q) /*sum the squares of the decimal digits*/
s=s + substr(q, j, 1) **2 /*add the square of a decimal digit.*/
end /*j*/
https://rosettacode.org/wiki/Happy_numbers 165/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
This REXX version also accepts a range of happy numbers to be shown, that is,
it can show the 2000th through the 2032nd (inclusive) happy numbers (as shown below).
https://rosettacode.org/wiki/Happy_numbers 166/210
4/4/2021 Happy numbers - Rosetta Code
https://rosettacode.org/wiki/Happy_numbers 167/210
4/4/2021 Happy numbers - Rosetta Code
13141
13142
13148
13158
13177
13182
13184
13185
13188
13203
13212
13214
13218
13221
13228
13230
13233
13241
13247
13248
13258
13266
13274
13281
13282
13284
13285
13299
13300
13302
13303
13305
13307
https://rosettacode.org/wiki/Happy_numbers 168/210
4/4/2021 Happy numbers - Rosetta Code
if !.s then do; !.n=1; iterate n; end /*is S unhappy? Then Q is also. */
if @.s then leave /*Have we found a happy number? */
q=s /*try the Q sum to see if it's happy.*/
end /*until*/
@.n=1 /*mark N as a happy number. */
haps=haps+1 /*bump the count of the happy numbers. */
if haps<L then iterate /*don't display it, N is too low. */
$=$ n /*add N to the horizontal list. */
if length($ n)>sw then do /*if the list is too long, then split */
say strip($) /* ··· and display what we've got. */
$=n /*Set the next line to overflow. */
end /* [↑] new line now contains overflow.*/
end /*n*/
if $\='' then say strip($) /*display any residual happy numbers. */
/*stick a fork in it, we're all done. */
This REXX program makes use of linesize REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
Some REXXes don't have this BIF, so the linesize.rex REXX program is included here ──► LINESIZE.REX (/wiki/LINESIZE.REX).
(The linesize for the terminal being used for this example was 200.)
https://rosettacode.org/wiki/Happy_numbers 169/210
4/4/2021 Happy numbers - Rosetta Code
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 103 109 129 130 133 139 167 176 188 190 192 193 203 208 219 226 230 236 239 262 263 280 291 293 301 302 310 313 319 320 326 329
362 365 367 368 376 379 383 386 391 392 397 404 409 440 446 464 469 478 487 490 496 536 556 563 565 566 608 617 622 623 632 635 637 638 644 649 653 655 656 665 671 673 680 683 694 700 709
748 761 763 784 790 793 802 806 818 820 833 836 847 860 863 874 881 888 899 901 904 907 910 912 913 921 923 931 932 937 940 946 964 970 973 989 998 1000 1003 1009 1029 1030 1033 1039 1067
1090 1092 1093 1112 1114 1115 1121 1122 1125 1128 1141 1148 1151 1152 1158 1177 1182 1184 1185 1188 1209 1211 1212 1215 1218 1221 1222 1233 1247 1251 1257 1258 1274 1275 1277 1281 1285 12
1300 1303 1309 1323 1330 1332 1333 1335 1337 1339 1353 1366 1373 1390 1393 1411 1418 1427 1444 1447 1448 1457 1472 1474 1475 1478 1481 1484 1487 1511 1512 1518 1521 1527 1528 1533 1547 15
1575 1578 1581 1582 1587 1599 1607 1636 1663 1666 1670 1679 1697 1706 1717 1724 1725 1727 1733 1742 1744 1745 1748 1752 1754 1755 1758 1760 1769 1771 1772 1784 1785 1796 1808 1812 1814 18
1825 1828 1841 1844 1847 1851 1852 1857 1874 1875 1880 1881 1882 1888 1900 1902 1903 1920 1929 1930 1933 1959 1967 1976 1992 1995 2003 2008 2019 2026 2030 2036 2039 2062 2063 2080 2091 20
2112 2115 2118 2121 2122 2133 2147 2151 2157 2158 2174 2175 2177 2181 2185 2188 2190 2199 2206 2211 2212 2221 2224 2242 2245 2254 2257 2258 2260 2275 2285 2300 2306 2309 2313 2331 2333 23
2369 2383 2390 2393 2396 2417 2422 2425 2448 2452 2455 2457 2458 2471 2475 2478 2484 2485 2487 2511 2517 2518 2524 2527 2528 2542 2545 2547 2548 2554 2555 2557 2568 2571 2572 2574 2575 25
2586 2602 2603 2620 2630 2639 2658 2685 2693 2714 2715 2717 2725 2741 2745 2748 2751 2752 2754 2755 2771 2784 2800 2811 2815 2818 2825 2833 2844 2845 2847 2851 2852 2854 2856 2865 2874 28
2903 2910 2919 2930 2933 2936 2963 2989 2991 2998 3001 3002 3010 3013 3019 3020 3026 3029 3031 3038 3056 3062 3065 3067 3068 3076 3079 3083 3086 3091 3092 3097 3100 3103 3109 3123 3130 31
3137 3139 3153 3166 3173 3190 3193 3200 3206 3209 3213 3231 3233 3238 3239 3260 3269 3283 3290 3293 3296 3301 3308 3310 3312 3313 3315 3317 3319 3321 3323 3328 3329 3331 3332 3338 3346 33
3364 3365 3367 3371 3376 3380 3382 3383 3391 3392 3436 3456 3463 3465 3466 3506 3513 3531 3535 3536 3546 3553 3560 3563 3564 3602 3605 3607 3608 3616 3620 3629 3634 3635 3637 3643 3645 36
3654 3661 3664 3667 3670 3673 3676 3680 3689 3692 3698 3706 3709 3713 3731 3736 3760 3763 3766 3779 3789 3790 3797 3798 3803 3806 3823 3830 3832 3833 3860 3869 3879 3896 3897 3901 3902 39
3920 3923 3926 3931 3932 3962 3968 3970 3977 3978 3986 3987 4004 4009 4040 4046 4064 4069 4078 4087 4090 4096 4111 4118 4127 4144 4147 4148 4157 4172 4174 4175 4178 4181 4184 4187 4217 42
4252 4255 4257 4258 4271 4275 4278 4284 4285 4287 4336 4356 4363 4365 4366 4400 4406 4414 4417 4418 4428 4441 4447 4449 4455 4460 4471 4474 4477 4481 4482 4494 4517 4522 4525 4527 4528 45
4554 4555 4558 4563 4571 4572 4577 4582 4585 4599 4604 4609 4633 4635 4636 4640 4653 4663 4690 4708 4712 4714 4715 4718 4721 4725 4728 4741 4744 4747 4751 4752 4757 4774 4775 4780 4781 47
4811 4814 4817 4824 4825 4827 4841 4842 4852 4855 4870 4871 4872 4878 4887 4888 4900 4906 4944 4959 4960 4995 5036 5056 5063 5065 5066 5111 5112 5118 5121 5127 5128 5133 5147 5157 5172 51
5181 5182 5187 5199 5211 5217 5218 5224 5227 5228 5242 5245 5247 5248 5254 5255 5257 5268 5271 5272 5274 5275 5281 5282 5284 5286 5306 5313 5331 5335 5336 5346 5353 5360 5363 5364 5417 54
5428 5436 5445 5452 5454 5455 5458 5463 5471 5472 5477 5482 5485 5499 5506 5517 5524 5525 5527 5533 5542 5544 5545 5548 5552 5554 5555 5558 5560 5569 5571 5572 5584 5585 5596 5603 5605 56
5633 5634 5643 5650 5659 5660 5666 5682 5695 5712 5714 5715 5718 5721 5722 5724 5725 5741 5742 5747 5751 5752 5774 5781 5789 5798 5799 5811 5812 5817 5821 5822 5824 5826 5842 5845 5854 58
5879 5897 5919 5949 5956 5965 5978 5979 5987 5991 5994 5997 6008 6017 6022 6023 6032 6035 6037 6038 6044 6049 6053 6055 6056 6065 6071 6073 6080 6083 6094 6107 6136 6163 6166 6170 6179 61
6220 6230 6239 6258 6285 6293 6302 6305 6307 6308 6316 6320 6329 6334 6335 6337 6343 6345 6346 6350 6353 6354 6361 6364 6367 6370 6373 6376 6380 6389 6392 6398 6404 6409 6433 6435 6436 64
6490 6503 6505 6506 6528 6530 6533 6534 6543 6550 6559 6560 6566 6582 6595 6605 6613 6616 6631 6634 6637 6643 6650 6656 6661 6665 6673 6701 6703 6710 6719 6730 6733 6736 6763 6789 6791 67
6825 6830 6839 6852 6879 6893 6897 6899 6904 6917 6923 6932 6938 6940 6955 6971 6978 6983 6987 6989 6998 7000 7009 7016 7036 7039 7048 7061 7063 7084 7090 7093 7106 7117 7124 7125 7127 71
7145 7148 7152 7154 7155 7158 7160 7169 7171 7172 7184 7185 7196 7214 7215 7217 7225 7241 7245 7248 7251 7252 7254 7255 7271 7284 7306 7309 7313 7331 7336 7360 7363 7366 7379 7389 7390 73
7412 7414 7415 7418 7421 7425 7428 7441 7444 7447 7451 7452 7457 7474 7475 7480 7481 7482 7488 7512 7514 7515 7518 7521 7522 7524 7525 7541 7542 7547 7551 7552 7574 7581 7589 7598 7599 76
7619 7630 7633 7636 7663 7689 7691 7698 7711 7712 7721 7739 7744 7745 7754 7788 7793 7804 7814 7815 7824 7839 7840 7841 7842 7848 7851 7859 7869 7878 7884 7887 7893 7895 7896 7900 7903 79
7938 7958 7959 7961 7968 7973 7983 7985 7986 7995 8002 8006 8018 8020 8033 8036 8047 8060 8063 8074 8081 8088 8099 8108 8112 8114 8115 8118 8121 8125 8128 8141 8144 8147 8151 8152 8157 81
8181 8182 8188 8200 8211 8215 8218 8225 8233 8244 8245 8247 8251 8252 8254 8256 8265 8274 8281 8299 8303 8306 8323 8330 8332 8333 8360 8369 8379 8396 8397 8407 8411 8414 8417 8424 8425 84
8452 8455 8470 8471 8472 8478 8487 8488 8511 8512 8517 8521 8522 8524 8526 8542 8545 8554 8555 8562 8571 8579 8597 8600 8603 8625 8630 8639 8652 8679 8693 8697 8699 8704 8714 8715 8724 87
8742 8748 8751 8759 8769 8778 8784 8787 8793 8795 8796 8801 8808 8810 8811 8812 8818 8821 8847 8848 8874 8877 8880 8881 8884 8909 8929 8936 8937 8957 8963 8967 8969 8973 8975 8976 8990 89
9004 9007 9010 9012 9013 9021 9023 9031 9032 9037 9040 9046 9064 9070 9073 9089 9098 9100 9102 9103 9120 9129 9130 9133 9159 9167 9176 9192 9195 9201 9203 9210 9219 9230 9233 9236 9263 92
9301 9302 9307 9310 9313 9320 9323 9326 9331 9332 9362 9368 9370 9377 9378 9386 9387 9400 9406 9444 9459 9460 9495 9519 9549 9556 9565 9578 9579 9587 9591 9594 9597 9604 9617 9623 9632 96
9671 9678 9683 9687 9689 9698 9700 9703 9716 9730 9737 9738 9758 9759 9761 9768 9773 9783 9785 9786 9795 9809 9829 9836 9837 9857 9863 9867 9869 9873 9875 9876 9890 9892 9896 9908 9912 99
9945 9951 9954 9957 9968 9975 9980 9982 9986 10000 10003 10009 10029 10030 10033 10039 10067 10076 10088 10090 10092 10093 10112 10114 10115 10121 10122 10125 10128 10141 10148 10151 1015
10177 10182 10184 10185 10188 10209 10211 10212 10215 10218 10221 10222 10233 10247 10251 10257 10258 10274 10275 10277 10281 10285 10288 10290 10299 10300 10303 10309 10323 10330 10332 1
10337
Ring (/wiki/Category:Ring)
https://rosettacode.org/wiki/Happy_numbers 170/210
4/4/2021 Happy numbers - Rosetta Code
n = 1
found = 0
Func IsHappy n
cache = []
While n != 1
Add(cache,n)
t = 0
strn = string(n)
for e in strn
t += pow(number(e),2)
next
n = t
If find(cache,n) Return False ok
End
Return True
Output:
1 : 1
2 : 7
3 : 10
4 : 13
5 : 19
6 : 23
7 : 28
8 : 31
Ruby (/wiki/Category:Ruby)
Works with: Ruby (/wiki/Ruby) version 2.1
https://rosettacode.org/wiki/Happy_numbers 171/210
4/4/2021 Happy numbers - Rosetta Code
@seen_numbers = Set.new
@happy_numbers = Set.new
def happy?(n)
return true if n == 1 # Base case
return @happy_numbers.include?(n) if @seen_numbers.include?(n) # Use performance cache, and stop unhappy cycles
@seen_numbers << n
digit_squared_sum = n.to_s.each_char.inject(0) { |sum, c| sum + c.to_i**2 } # In Rails: n.to_s.each_char.sum { c.to_i**2 }
if happy?(digit_squared_sum)
@happy_numbers << n
true # Return true
else
false # Return false
end
end
def print_happy
happy_numbers = []
1.step do |i|
break if happy_numbers.length >= 8
happy_numbers << i if happy?(i)
end
p happy_numbers
end
print_happy
Output:
Alternative version
https://rosettacode.org/wiki/Happy_numbers 172/210
4/4/2021 Happy numbers - Rosetta Code
@memo = [0,1]
def happy(n)
sum = n.to_s.chars.map{|c| c.to_i**2}.inject(:+)
return @memo[sum] if @memo[sum]==0 or @memo[sum]==1
@memo[sum] = 0 # for the cycle check
@memo[sum] = happy(sum) # return 1:Happy number, 0:other
end
i = count = 0
while count < 8
i += 1
puts i or count+=1 if happy(i)==1
end
puts
for i in 99999999999900..99999999999999
puts i if happy(i)==1
end
Output:
1
7
10
13
19
23
28
31
99999999999901
99999999999910
99999999999914
99999999999915
99999999999916
99999999999937
99999999999941
99999999999951
99999999999956
99999999999961
99999999999965
99999999999973
https://rosettacode.org/wiki/Happy_numbers 173/210
4/4/2021 Happy numbers - Rosetta Code
Simpler Alternative
Translation of: Python
def happy?(n)
past = []
until n == 1
n = n.digits.sum { |d| d * d }
return false if past.include? n
past << n
end
true
end
i = count = 0
until count == 8; puts i or count += 1 if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }
Output:
1
7
10
13
19
23
28
31
99999999999901
99999999999910
99999999999914
99999999999915
99999999999916
99999999999937
99999999999941
99999999999951
99999999999956
99999999999961
99999999999965
99999999999973
https://rosettacode.org/wiki/Happy_numbers 174/210
4/4/2021 Happy numbers - Rosetta Code
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
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
Rust (/wiki/Category:Rust)
In Rust, using a tortoise/hare cycle detection algorithm (generic for integer types)
https://rosettacode.org/wiki/Happy_numbers 175/210
4/4/2021 Happy numbers - Rosetta Code
#![feature(core)]
use std::num::Int;
fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T {
let mut t = a;
let mut h = f(a);
while t != h {
t = f(t);
h = f(f(h))
}
t
}
fn main() {
let happy = std::iter::count(1, 1)
.filter(|&n| ishappy(n))
.take(8)
.collect::<Vec<i32>>();
println!("{:?}", happy)
}
Output:
https://rosettacode.org/wiki/Happy_numbers 176/210
4/4/2021 Happy numbers - Rosetta Code
Salmon (/wiki/Category:Salmon)
variable happy_count := 0;
outer:
iterate(x; [1...+oo])
{
variable seen := <<(* --> false)>>;
variable now := x;
while (true)
{
if (seen[now])
{
if (now == 1)
{
++happy_count;
print(x, " is happy.\n");
if (happy_count == 8)
break from outer;;
};
break;
};
seen[now] := true;
variable new := 0;
while (now != 0)
{
new += (now % 10) * (now % 10);
now /::= 10;
};
now := new;
};
};
https://rosettacode.org/wiki/Happy_numbers 177/210
4/4/2021 Happy numbers - Rosetta Code
1 is happy.
7 is happy.
10 is happy.
13 is happy.
19 is happy.
23 is happy.
28 is happy.
31 is happy.
Scala (/wiki/Category:Scala)
scala> def (https://scala-lang.org) isHappy(n: Int) = {
| new (https://scala-lang.org) Iterator[Int] {
| val (https://scala-lang.org) seen = scala.collection.mutable.Set[Int]()
| var (https://scala-lang.org) curr = n
| def (https://scala-lang.org) next = {
| val (https://scala-lang.org) res = curr
| curr = res.toString.map(_.asDigit).map(n => n * n).sum
| seen += res
| res
| }
| def (https://scala-lang.org) hasNext = !seen.contains(curr)
| }.toList.last == 1
| }
isHappy: (n: Int)Boolean
Scheme (/wiki/Category:Scheme)
https://rosettacode.org/wiki/Happy_numbers 178/210
4/4/2021 Happy numbers - Rosetta Code
happy numbers: 1 7 10 13 19 23 28 31
Scratch (/wiki/Category:Scratch)
Scratch is a free visual programming language. Click the link, then "See inside" to view the code.
https://scratch.mit.edu/projects/78912620/ (https://scratch.mit.edu/projects/78912620/)
This code will allow you to check if a positive interger (<=9999) is a happy number. It will also output a list of the first 8 happy numbers. (1 7 10 13 19 23 28
31)
Seed7 (/wiki/Category:Seed7)
https://rosettacode.org/wiki/Happy_numbers 179/210
4/4/2021 Happy numbers - Rosetta Code
$ include "seed7_05.s7i";
https://rosettacode.org/wiki/Happy_numbers 180/210
4/4/2021 Happy numbers - Rosetta Code
Output:
1
7
10
13
19
23
28
31
32
44
49
SequenceL (/wiki/Category:SequenceL)
https://rosettacode.org/wiki/Happy_numbers 181/210
4/4/2021 Happy numbers - Rosetta Code
import <Utilities/Math.sl>;
import <Utilities/Conversion.sl>;
main(argv(2)) := findHappys(stringToInt(head(argv)));
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);
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]);
Output:
$>happy.exe 8
[1,7,10,13,19,23,28,31]
SETL (/wiki/Category:SETL)
https://rosettacode.org/wiki/Happy_numbers 182/210
4/4/2021 Happy numbers - Rosetta Code
proc is_happy(n);
s := [n];
while n > 1 loop
if (n := +/[val(i)**2: i in str(n)]) in s then
return false;
end if;
s with:= n;
end while;
return true;
end proc;
happy := [];
n := 1;
until #happy = 8 loop
if is_happy(n) then happy with:= n; end if;
n +:= 1;
end loop;
print(happy);
Output:
[1 7 10 13 19 23 28 31]
Alternative version:
Output:
[1 7 10 13 19 23 28 31]
Sidef (/wiki/Category:Sidef)
https://rosettacode.org/wiki/Happy_numbers 183/210
4/4/2021 Happy numbers - Rosetta Code
seen{n} = 1
happy(n.digits.sum { _*_ })
}
say happy.first(8)
Output:
Smalltalk (/wiki/Category:Smalltalk)
Works with: GNU Smalltalk (/wiki/GNU_Smalltalk)
Translation of: 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.
https://rosettacode.org/wiki/Happy_numbers 184/210
4/4/2021 Happy numbers - Rosetta Code
hasSad: aNum [
^ (negativeCache includes: (self recycle: aNum))
]
hasHappy: aNum [
^ (cache includes: (self recycle: aNum))
]
addHappy: aNum [
cache add: (self recycle: aNum)
]
addSad: aNum [
negativeCache add: (self recycle: aNum)
]
https://rosettacode.org/wiki/Happy_numbers 185/210
4/4/2021 Happy numbers - Rosetta Code
[ number > 0 ]
whileTrue: [ |digit|
digit := number rem: 10.
newnumber := newnumber + (digit * digit).
number := (number - digit) // 10.
].
number := newnumber.
]
].
(number = 1)
ifTrue: [
cycle do: [ :e | self addHappy: e ].
^true
]
ifFalse: [
cycle do: [ :e | self addSad: e ].
^false
]
]
].
|happy|
happy := HappyNumber new.
1 to: 31 do: [ :i |
(happy isHappy: i)
ifTrue: [ i displayNl ]
].
Output:
1
7
10
13
19
23
28
31
https://rosettacode.org/wiki/Happy_numbers 186/210
4/4/2021 Happy numbers - Rosetta Code
next :=
[:n |
(n printString collect:[:ch | ch digitValue squared] as:Array) sum
].
isHappy :=
[:n | | t already |
already := Set new.
t := n.
[ t == 1 or:[ (already includes:t)]] whileFalse:[
already add:t.
t := next value:t.
].
t == 1
].
Swift (/wiki/Category:Swift)
https://rosettacode.org/wiki/Happy_numbers 187/210
4/4/2021 Happy numbers - Rosetta Code
var found = 0
var count = 0
while found != 8 {
if isHappyNumber(count) {
print(count)
found++
}
count++
}
Output:
1
7
10
13
19
23
28
31
Tcl (/wiki/Category:Tcl)
using code from Sum of squares#Tcl (/wiki/Sum_of_squares#Tcl)
https://rosettacode.org/wiki/Happy_numbers 188/210
4/4/2021 Happy numbers - Rosetta Code
proc is_happy n {
set seen [list]
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
lappend seen $n
set n [sum_of_squares [split $n ""]]
}
return [expr {$n == 1}]
}
TUSCRIPT (/wiki/Category:TUSCRIPT)
https://rosettacode.org/wiki/Happy_numbers 189/210
4/4/2021 Happy numbers - Rosetta Code
$$ MODE TUSCRIPT
SECTION check
IF (n!=1) THEN
n = STRINGS (n,":>/:")
LOOP/CLEAR nr=n
square=nr*nr
n=APPEND (n,square)
ENDLOOP
n=SUM(n)
r_table=QUOTES (n)
BUILD R_TABLE/word/EXACT chk=r_table
IF (seq.ma.chk) THEN
status="next"
ELSE
seq=APPEND (seq,n)
ENDIF
RELEASE r_table chk
ELSE
PRINT checkednr," is a happy number"
happynrs=APPEND (happynrs,checkednr)
status="next"
ENDIF
ENDSECTION
happynrs=""
LOOP n=1,100
sz_happynrs=SIZE(happynrs)
IF (sz_happynrs==8) EXIT
checkednr=VALUE(n)
status=seq=""
LOOP
IF (status=="next") EXIT
DO check
ENDLOOP
ENDLOOP
Output:
https://rosettacode.org/wiki/Happy_numbers 190/210
4/4/2021 Happy numbers - Rosetta Code
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
uBasic/4tH (/wiki/Category:UBasic/4tH)
https://rosettacode.org/wiki/Happy_numbers 191/210
4/4/2021 Happy numbers - Rosetta Code
' ************************
' 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
' --------------------
_PRINT_HAPPY PARAM(1)
' --------------------
https://rosettacode.org/wiki/Happy_numbers 192/210
4/4/2021 Happy numbers - Rosetta Code
LOCAL (2)
b@ = 1
c@ = 0
DO
b@ = b@ + 1
UNTIL c@ + 1 > a@
LOOP
RETURN
' ************************
' END SUBS & FUNCTIONS
' ************************
https://rosettacode.org/wiki/Happy_numbers 193/210
4/4/2021 Happy numbers - Rosetta Code
#!/bin/bash
function sum_of_square_digits
{
local -i n="$1" sum=0
while (( n )); do
local -i d=n%10
let sum+=d*d
let n=n/10
done
echo "$sum"
}
function is_happy?
{
local -i n="$1"
local seen=()
while (( n != 1 )); do
if [ -n "${seen[$n]}" ]; then
return 1
fi
seen[n]=1
let n="$(sum_of_square_digits "$n")"
done
return 0
}
function first_n_happy
{
local -i count="$1"
local -i n
for (( n=0; count; n+=1 )); do
if is_happy? "$n"; then
echo "$n"
let count-=1
fi
done
return 0
}
first_n_happy 8
Output:
https://rosettacode.org/wiki/Happy_numbers 194/210
4/4/2021 Happy numbers - Rosetta Code
1
7
10
13
19
23
28
31
Ursala (/wiki/Category:Ursala)
The happy function is a predicate testing whether a given number is happy, and first(p) defines a function mapping a number n to the first n positive naturals
having property p.
#import std
#import nat
first "p" = ~&i&& iota; ~&lrtPX/&; leql@lrPrX->lrx ^|\~& ^/successor@l ^|T\~& "p"&& ~&iNC
#cast %nL
output:
<1,7,10,13,19,23,28,31>
Vala (/wiki/Category:Vala)
Library: Gee (/mw/index.php?title=Category:Gee&action=edit&redlink=1)
https://rosettacode.org/wiki/Happy_numbers 195/210
4/4/2021 Happy numbers - Rosetta Code
using Gee;
return total;
} // end sum
if (total in past){
return false;}
past.add(total);
} // end while loop
} // end happy
https://rosettacode.org/wiki/Happy_numbers 196/210
4/4/2021 Happy numbers - Rosetta Code
1 7 10 13 19 23 28 31
VBA (/wiki/Category:VBA)
https://rosettacode.org/wiki/Happy_numbers 197/210
4/4/2021 Happy numbers - Rosetta Code
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
Output:
Is Happy : 1
Is Happy : 7
Is Happy : 10
Is Happy : 13
Is Happy : 19
Is Happy : 23
Is Happy : 28
Is Happy : 31
https://rosettacode.org/wiki/Happy_numbers 198/210
4/4/2021 Happy numbers - Rosetta Code
VBScript (/wiki/Category:VBScript)
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
Output:
1,7,10,13,19,23,28,31,
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
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
1: 1
2: 7
3: 10
4: 13
5: 19
6: 23
7: 28
8: 31
https://rosettacode.org/wiki/Happy_numbers 200/210
4/4/2021 Happy numbers - Rosetta Code
Cacheless version
Translation of: C#
Curiously, this runs in about two thirds of the time of the cacheless C# version on Tio.run.
https://rosettacode.org/wiki/Happy_numbers 201/210
4/4/2021 Happy numbers - Rosetta Code
Module Module1
Output:
https://rosettacode.org/wiki/Happy_numbers 202/210
4/4/2021 Happy numbers - Rosetta Code
---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.
Wren (/wiki/Category:Wren)
Translation of: Go
var found = 0
var n = 1
while (found < 8) {
if (happy.call(n)) {
System.write("%(n) ")
found = found + 1
}
n = n + 1
}
System.print()
https://rosettacode.org/wiki/Happy_numbers 203/210
4/4/2021 Happy numbers - Rosetta Code
Output:
1 7 10 13 19 23 28 31
XPL0 (/wiki/Category:XPL0)
The largest possible 32-bit integer is less than 9,999,999,999. The sum of the squares of these ten digits is 10*9^2 = 810. If a cycle consisted of all the
values smaller than 810, an array size of 810 would still be sufficiently large to hold them. Actually, tests show that the array only needs to hold 16 numbers.
https://rosettacode.org/wiki/Happy_numbers 204/210
4/4/2021 Happy numbers - Rosetta Code
int N0, N, C;
[N0:= 0; \starting number
C:= 0; \initialize happy (starting) number counter
repeat N:= N0;
Inx:= 0; \reset List index
loop [N:= SqDigits(N);
if N = 1 then \happy number
[IntOut(0, N0); CrLf(0);
C:= C+1;
quit;
];
if HadNum(N) then quit; \if unhappy number then quit
List(Inx):= N; \if neither, add it to the List
Inx:= Inx+1; \ and continue the cycle
];
N0:= N0+1; \next starting number
https://rosettacode.org/wiki/Happy_numbers 205/210
4/4/2021 Happy numbers - Rosetta Code
Output:
1
7
10
13
19
23
28
31
Zig (/wiki/Category:Zig)
https://rosettacode.org/wiki/Happy_numbers 206/210
4/4/2021 Happy numbers - Rosetta Code
Output:
https://rosettacode.org/wiki/Happy_numbers 207/210
4/4/2021 Happy numbers - Rosetta Code
zkl (/wiki/Category: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).
h:=Utils.Generator(happyNumbers);
h.walk(8).println();
Output:
L(1,7,10,13,19,23,28,31)
Get the one million-th happy number. Nobody would call this quick.
Utils.Generator(happyNumbers).drop(0d1_000_000-1).next().println();
Output:
7105849
https://rosettacode.org/wiki/Happy_numbers 208/210
4/4/2021 Happy numbers - Rosetta Code
https://rosettacode.org/wiki/Happy_numbers 209/210
4/4/2021 Happy numbers - Rosetta Code
(https://www.gnu.org/licenses/fdl-1.2.html) (//www.mediawiki.org/)
(https://www.semantic-mediawiki.org/wiki/Semantic_MediaWiki)
https://rosettacode.org/wiki/Happy_numbers 210/210