Happy numbers: Difference between revisions

m
syntax highlighting fixup automation
(Applesoft BASIC)
m (syntax highlighting fixup automation)
Line 24:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F happy(=n)
Set[Int] past
L n != 1
Line 33:
R 1B
 
print((0.<500).filter(x -> happy(x))[0.<8])</langsyntaxhighlight>
 
{{out}}
Line 52:
under 256, the cycle never goes above 163; this program could be trivially changed to print up to 39 happy numbers.
 
<langsyntaxhighlight lang="8080asm">flags: equ 2 ; 256-byte page in which to keep track of cycles
puts: equ 9 ; CP/M print string
bdos: equ 5 ; CP/M entry point
Line 128:
adi 10
ret ; 1s digit is left in A afterwards
string: db '000',13,10,'$'</langsyntaxhighlight>
 
{{out}}
Line 143:
 
=={{header|8th}}==
<langsyntaxhighlight lang="8th">
: until! "not while!" eval i;
 
Line 173:
;with
;with
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 181:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(include-book "arithmetic-3/top" :dir :system)
 
(defun sum-of-digit-squares (n)
Line 205:
 
(defun first-happy-nums (n)
(first-happy-nums-r n 1))</langsyntaxhighlight>
Output:
<pre>(1 7 10 13 19 23 28 31)</pre>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC SumOfSquares(BYTE x)
BYTE sum,d
 
Line 260:
x==+1
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Happy_numbers.png Screenshot from Atari 8-bit computer]
Line 275:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function sumOfSquares(n:uint)
{
var sum:uint = 0;
Line 316:
}
}
printHappy();</langsyntaxhighlight>
Sample output:
<pre>
Line 330:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
 
Line 370:
end if;
end loop;
end Test_Happy_Digits;</langsyntaxhighlight>
Sample output:
<pre>
Line 380:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">INT base10 = 10, num happy = 8;
 
PROC next = (INT in n)INT: (
Line 404:
print((i, new line))
FI
OD</langsyntaxhighlight>
Output:
<pre>
Line 418:
 
=={{header|ALGOL-M}}==
<langsyntaxhighlight lang="algolm">begin
integer function mod(a,b);
integer a,b;
Line 455:
i := i + 1;
end;
end</langsyntaxhighlight>
{{out}}
<pre> 1
Line 467:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% find some happy numbers %
% returns true if n is happy, false otherwise; n must be >= 0 %
Line 520:
end while_happyCount_lt_8
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 529:
 
===Tradfn===
<langsyntaxhighlight APLlang="apl"> ∇ HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
[1] ⍝0: Happy number
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
Line 548:
[17]
[18] ⎕←~∘0¨∆first↑bin/iroof ⍝ Show ∆first numbers, but not 0
∇</langsyntaxhighlight>
<pre>
HappyNumbers 100 8
Line 555:
 
===Dfn===
<syntaxhighlight lang="apl">
<lang APL>
HappyNumbers←{ ⍝ return the first ⍵ Happy Numbers
⍺←⍬ ⍝ initial list
Line 570:
HappyNumbers 8
1 7 10 13 19 23 28 31
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
 
===Iteration===
<langsyntaxhighlight AppleScriptlang="applescript">on run
set howManyHappyNumbers to 8
set happyNumberList to {}
Line 606:
end repeat
return (numberToCheck = 1)
end isHappy</langsyntaxhighlight>
<pre>
Result: (*1, 7, 10, 13, 19, 23, 28, 31*)
Line 614:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">---------------------- HAPPY NUMBERS -----------------------
 
-- isHappy :: Int -> Bool
Line 740:
end tell
return v
end |until|</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{1, 7, 10, 13, 19, 23, 28, 31}</langsyntaxhighlight>
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight lang="gwbasic"> 0 C = 8: DIM S(16):B = 10: PRINT "THE FIRST "C" HAPPY NUMBERS": FOR R = C TO 0 STEP 0:N = H: GOSUB 1: PRINT MID$ (" " + STR$ (H),1 + (R = C),255 * I);:R = R - I:H = H + 1: NEXT R: END
1 S = 0: GOSUB 3:I = N = 1: IF NOT Q THEN RETURN
2 FOR Q = 1 TO 0 STEP 0:S(S) = N:S = S + 1: GOSUB 6:N = T: GOSUB 3: NEXT Q:I = N = 1: RETURN
Line 751:
4 Q = 0: FOR I = 0 TO S - 1: IF N = S(I) THEN RETURN
5 NEXT I:Q = 1: RETURN
6 T = 0: FOR I = N TO 0 STEP 0:M = INT (I / B):T = INT (T + (I - M * B) ^ 2):I = M: NEXT I: RETURN</langsyntaxhighlight>
{{out}}
<pre>
Line 761:
{{trans|Nim}}
 
<langsyntaxhighlight lang="rebol">ord0: to :integer `0`
happy?: function [x][
n: x
Line 781:
loop 0..31 'x [
if happy? x -> print x
]</langsyntaxhighlight>
 
{{out}}
Line 795:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop {
If isHappy(A_Index) {
out .= (out="" ? "" : ",") . A_Index
Line 815:
Return false
Else Return isHappy(sum, list)
}</langsyntaxhighlight>
<pre>
The first 8 happy numbers are: 1,7,10,13,19,23,28,31
</pre>
===Alternative version===
<langsyntaxhighlight AutoHotkeylang="autohotkey">while h < 8
if (Happy(A_Index)) {
Out .= A_Index A_Space
Line 837:
n := t, t := 0
}
}</langsyntaxhighlight>
<pre>1 7 10 13 19 23 28 31</pre>
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">
$c = 0
$k = 0
Line 864:
EndIf
WEnd
</syntaxhighlight>
</lang>
 
<pre>
Line 880:
 
===Alternative version===
<langsyntaxhighlight lang="autoit">
$c = 0
$k = 0
Line 905:
$a.Clear
WEnd
</syntaxhighlight>
</lang>
<pre>
Saves all numbers in a list, duplicate entry indicates a loop.
Line 920:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function is_happy(n)
{
if ( n in happy ) return 1;
Line 960:
}
}
}</langsyntaxhighlight>
Result:
<pre>1
Line 975:
Alternately, for legibility one might write:
 
<langsyntaxhighlight lang="awk">BEGIN {
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
Line 1,002:
}
return tot
}</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<langsyntaxhighlight lang="freebasic">n = 1 : cnt = 0
print "The first 8 isHappy numbers are:"
print
Line 1,029:
num = isHappy
end while
end function</langsyntaxhighlight>
 
=={{header|Batch File}}==
happy.bat
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
::Define a list with 10 terms as a convenience for defining a loop
Line 1,113:
)
set /a n=sum
)</langsyntaxhighlight>
Sample usage and output
<pre>
Line 1,173:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> number% = 0
total% = 0
REPEAT
Line 1,193:
num% = MOD(digit&())^2 + 0.5
UNTIL num% = 1 OR num% = 4
= (num% = 1)</langsyntaxhighlight>
Output:
<pre> 1 is a happy number
Line 1,205:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let sumdigitsq(n) =
Line 1,229:
$)
wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
 
=={{header|Bori}}==
<langsyntaxhighlight lang="bori">bool isHappy (int n)
{
ints cache;
Line 1,269:
}
puts("First 8 happy numbers : " + str.newline + happynums);
}</langsyntaxhighlight>
Output:
<pre>First 8 happy numbers :
Line 1,275:
 
=={{header|BQN}}==
<langsyntaxhighlight lang="bqn">SumSqDgt ← +´2⋆˜ •Fmt-'0'˙
Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢
8↑Happy¨⊸/↕50</langsyntaxhighlight>
{{out}}
<pre>⟨ 1 7 10 13 19 23 28 31 ⟩</pre>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">include :set
 
happiness = set.new 1
Line 1,310:
p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"</langsyntaxhighlight>
Output:
<pre>First eight happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]
Line 1,318:
=={{header|C}}==
Recursively look up if digit square sum is happy.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define CACHE 256
Line 1,350:
 
return 0;
}</langsyntaxhighlight>
output<pre>1 7 10 13 19 23 28 31
The 1000000th happy number: 7105849</pre>
Without caching, using cycle detection:
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int dsum(int n)
Line 1,384:
 
return 0;
}</langsyntaxhighlight> Output is same as above, but much slower.
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,435:
}
}
}</langsyntaxhighlight>
<pre>
First 8 happy numbers : 1,7,10,13,19,23,28,31
Line 1,442:
===Alternate (cacheless)===
Instead of caching and checking for being stuck in a loop, one can terminate on the "unhappy" endpoint of 89. One might be temped to try caching the so-far-found happy and unhappy numbers and checking the cache to speed things up. However, I have found that the cache implementation overhead reduces performance compared to this cacheless version.<br/>
Reaching 10 million, the <34 second computation time was from Tio.run. It takes under 5 seconds on a somewhat modern CPU. If you edit it to max out at 100 million, it takes about 50 seconds (on the somewhat modern CPU).<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
class Program
Line 1,475:
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}</langsyntaxhighlight>
{{out}}
<pre>---Happy Numbers---
Line 1,490:
=={{header|C++}}==
{{trans|Python}}
<langsyntaxhighlight lang="cpp">#include <map>
#include <set>
 
Line 1,525:
std::cout << i << std::endl;
return 0;
}</langsyntaxhighlight>
Output:
<pre>1
Line 1,539:
49</pre>
Alternative version without caching:
<langsyntaxhighlight lang="cpp">unsigned int happy_iteration(unsigned int n)
{
unsigned int result = 0;
Line 1,579:
}
std::cout << std::endl;
}</langsyntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 1,585:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn happy? [n]
(loop [n n, seen #{}]
(cond
Line 1,599:
(def happy-numbers (filter happy? (iterate inc 1)))
 
(println (take 8 happy-numbers))</langsyntaxhighlight>
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
===Alternate Version (with caching)===
<langsyntaxhighlight lang="clojure">(require '[clojure.set :refer [union]])
 
(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})})
Line 1,636:
(filter #(= :happy (happy-algo %)))))
 
(println (take 8 happy-numbers))</langsyntaxhighlight>
Same output.
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">sum_dig_sq = proc (n: int) returns (int)
sum_sq: int := 0
while n > 0 do
Line 1,675:
stream$putl(po, int$unparse(i))
end
end start_up </langsyntaxhighlight>
{{out}}
<pre>1
Line 1,687:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">happy = (n) ->
seen = {}
while true
Line 1,708:
console.log i
cnt += 1
i += 1</langsyntaxhighlight>
output
<pre>
Line 1,723:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun sqr (n)
(* n n))
 
Line 1,744:
(print (happys))
</syntaxhighlight>
</lang>
 
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub sumDigitSquare(n: uint8): (s: uint8) is
Line 1,786:
end if;
n := n + 1;
end loop;</langsyntaxhighlight>
 
{{out}}
Line 1,801:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">def happy?(n)
past = [] of Int32 | Int64
until n == 1
Line 1,814:
until count == 8; (puts i; count += 1) if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</langsyntaxhighlight>
{{out}}
<pre>
Line 1,840:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">bool isHappy(int n) pure nothrow {
int[int] past;
 
Line 1,862:
 
int.max.iota.filter!isHappy.take(8).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
===Alternative Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.conv, std.string;
 
bool isHappy(int n) pure nothrow {
Line 1,884:
void main() {
int.max.iota.filter!isHappy.take(8).writeln;
}</langsyntaxhighlight>
Same output.
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">main() {
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
Line 1,922:
i++;
}
}</langsyntaxhighlight>
 
=={{header|dc}}==
<langsyntaxhighlight lang="dc">[lcI~rscd*+lc0<H]sH
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx</langsyntaxhighlight>
Output:
<pre>1
Line 1,940:
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ happy_1 = 1
$ found = 0
$ i = 1
Line 1,989:
$ goto loop1
$ done:
$ show symbol found*</langsyntaxhighlight>
{{out}}
<pre> FOUND = 8 Hex = 00000008 Octal = 00000000010
Line 2,004:
{{libheader| Boost.Int}}
Adaptation of [[#Pascal]]. The lib '''Boost.Int''' can be found here [https://github.com/MaiconSoft/DelphiBoostLib]
<syntaxhighlight lang="delphi">
<lang Delphi>
program Happy_numbers;
 
Line 2,068:
writeln;
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec dsumsq(byte n) byte:
byte r, d;
r := 0;
Line 2,105:
n := n + 1
od
corp</langsyntaxhighlight>
{{out}}
<pre> 1
Line 2,117:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">function IsHappy(n : Integer) : Boolean;
var
cache : array of Integer;
Line 2,146:
Dec(n);
end;
end;</langsyntaxhighlight>
Output:
<pre>1
Line 2,159:
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">func happy(n) {
var m = []
while n > 1 {
Line 2,185:
n += 1
}
print()</langsyntaxhighlight>
 
{{out}}
Line 2,192:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">next-num:
0
while over:
Line 2,228:
++
drop
drop</langsyntaxhighlight>
{{output}}
<pre>A happy number: 1
Line 2,241:
=={{header|E}}==
{{output?|E}}
<langsyntaxhighlight lang="e">def isHappyNumber(var x :int) {
var seen := [].asSet()
while (!seen.contains(x)) {
Line 2,260:
println(x)
if ((count += 1) >= 8) { break }
}</langsyntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 2,335:
end
 
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<langsyntaxhighlight lang="elena">import extensions;
import system'collections;
import system'routines;
Line 2,383:
};
console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,390:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Happy do
def task(num) do
Process.put({:happy, 1}, true)
Line 2,416:
end
 
IO.inspect Happy.task(8)</langsyntaxhighlight>
 
{{out}}
Line 2,424:
 
=={{header|Erlang}}==
<langsyntaxhighlight Erlanglang="erlang">-module(tasks).
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
Line 2,456:
main() ->
main(0, []).
</syntaxhighlight>
</lang>
Command: <langsyntaxhighlight Bashlang="bash">erl -run tasks main -run init stop -noshell</langsyntaxhighlight>
Output: <langsyntaxhighlight Bashlang="bash">8 Happy Numbers: [1,7,10,13,19,23,28,31]</langsyntaxhighlight>
 
In a more functional style (assumes integer_to_list/1 will convert to the ASCII value of a number, which then has to be converted to the integer value by subtracting 48):
<langsyntaxhighlight Erlanglang="erlang">-module(tasks).
 
-export([main/0]).
Line 2,478:
N_As_Digits = [Y - 48 || Y <- integer_to_list(N)],
is_happy(lists:foldl(fun(X, Sum) -> (X * X) + Sum end, 0, N_As_Digits));
is_happy(_) -> false.</langsyntaxhighlight>
Output:
<pre>[1,7,10,13,19,23,28,31]</pre>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function is_happy(integer n)
sequence seen
integer k
Line 2,511:
end if
n += 1
end while</langsyntaxhighlight>
Output:
<pre>1
Line 2,525:
=={{header|F_Sharp|F#}}==
This requires the F# power pack to be referenced and the 2010 beta of F#
<langsyntaxhighlight lang="fsharp">open System.Collections.Generic
open Microsoft.FSharp.Collections
 
Line 2,554:
|> Seq.truncate 8 // Stop when we've found 8
|> Seq.iter (Printf.printf "%d\n") // Print results
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,568:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: combinators kernel make math sequences ;
 
: squares ( n -- s )
Line 2,588:
dup happy? [ dup , [ 1 - ] dip ] when 1 +
] while 2drop
] { } make ;</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="factor">8 happy-numbers ! { 1 7 10 13 19 23 28 31 }</langsyntaxhighlight>
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[$10/$10*@\-$*\]m: {modulo squared and division}
[$m;![$9>][m;!@@+\]#$*+]s: {sum of squares}
[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates}
Line 2,607:
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%</langsyntaxhighlight>
 
{{out}}
Line 2,613:
 
=={{header|Fantom}}==
<langsyntaxhighlight lang="fantom">class Main
{
static Bool isHappy (Int n)
Line 2,648:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,662:
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="focal">01.10 S J=0;S N=1;T %2
01.20 D 3;I (K-2)1.5
01.30 S N=N+1
Line 2,680:
03.30 S S(K)=0
03.40 D 2;S K=R
03.50 I (S(K))3.3</langsyntaxhighlight>
 
{{out}}
Line 2,694:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: next ( n -- n )
0 swap begin 10 /mod >r dup * + r> ?dup 0= until ;
 
Line 2,713:
loop drop ;
 
8 happy-numbers \ 1 7 10 13 19 23 28 31</langsyntaxhighlight>
 
===Lookup Table===
Every sequence either ends in 1, or contains a 4 as part of a cycle. Extending the table through 9 is a (modest) optimization/memoization. This executes '500000 happy-numbers' about 5 times faster than the above solution.
<langsyntaxhighlight lang="forth">CREATE HAPPINESS 0 C, 1 C, 0 C, 0 C, 0 C, 0 C, 0 C, 1 C, 0 C, 0 C,
: next ( n -- n')
0 swap BEGIN dup WHILE 10 /mod >r dup * + r> REPEAT drop ;
Line 2,726:
BEGIN 1+ dup happy? UNTIL dup . r> 1- >r
REPEAT r> drop drop ;
8 happy-numbers</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Produces the 1 millionth happy number with:
<langsyntaxhighlight lang="forth">: happy-number ( n -- n') \ produce the nth happy number
>r 0 BEGIN r@ WHILE
BEGIN 1+ dup happy? UNTIL r> 1- >r
REPEAT r> drop ;
1000000 happy-number . \ 7105849</langsyntaxhighlight>
in about 9 seconds.
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program happy
 
implicit none
Line 2,804:
end function is_happy
 
end program happy</langsyntaxhighlight>
Output:
<pre>1
Line 2,816:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function isHappy(n As Integer) As Boolean
Line 2,859:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 2,878:
{{Works with|Frege|3.21.586-g026e8d7}}
 
<langsyntaxhighlight lang="frege">module Happy where
 
import Prelude.Math
Line 2,894:
f = sum . map (sqr . digitToInteger) . unpacked . show
 
main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n</langsyntaxhighlight>
 
{{out}}
Line 2,912:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,940:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,947:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">Number.metaClass.isHappy = {
def number = delegate as Long
def cycle = new HashSet<Long>()
Line 2,961:
if (i.happy) { matches << i }
}
println matches</langsyntaxhighlight>
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="xbase">PROCEDURE Main()
LOCAL i := 8, nH := 0
 
Line 2,998:
AAdd( aUnhappy, nSum )
 
RETURN IsHappy( nSum )</langsyntaxhighlight>
Output:
 
Line 3,005:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (digitToInt)
import Data.Set (member, insert, empty)
 
Line 3,018:
 
main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]</langsyntaxhighlight>
{{Out}}
<pre>1
Line 3,030:
 
We can create a cache for small numbers to greatly speed up the process:
<langsyntaxhighlight lang="haskell">import Data.Array (Array, (!), listArray)
 
happy :: Int -> Bool
Line 3,048:
 
main :: IO ()
main = print $ sum $ take 10000 $ filter happy [1 ..]</langsyntaxhighlight>
{{Out}}
<pre>327604323</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
local n
n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8
Line 3,069:
if happy(n) then return i
}
end</langsyntaxhighlight>
Usage and Output:
<pre>
Line 3,078:
 
=={{header|J}}==
<langsyntaxhighlight lang="j"> 8{. (#~1=+/@(*:@(,.&.":))^:(1&~:*.4&~:)^:_ "0) 1+i.100
1 7 10 13 19 23 28 31</langsyntaxhighlight>
This is a repeat while construction
<langsyntaxhighlight lang="j"> f ^: cond ^: _ input</langsyntaxhighlight>
that produces an array of 1's and 4's, which is converted to 1's and 0's forming a binary array having a 1 for a happy number. Finally the happy numbers are extracted by a binary selector.
<langsyntaxhighlight lang="j"> (binary array) # 1..100</langsyntaxhighlight>
So for easier reading the solution could be expressed as:
<langsyntaxhighlight lang="j"> cond=: 1&~: *. 4&~: NB. not equal to 1 and not equal to 4
sumSqrDigits=: +/@(*:@(,.&.":))
 
Line 3,091:
14
8{. (#~ 1 = sumSqrDigits ^: cond ^:_ "0) 1 + i.100
1 7 10 13 19 23 28 31</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
{{trans|JavaScript}}
<langsyntaxhighlight lang="java5">import java.util.HashSet;
public class Happy{
public static boolean happy(long number){
Line 3,122:
}
}
}</langsyntaxhighlight>
Output:
<pre>1
Line 3,137:
{{works with|Java|1.8}}
{{trans|Java}}
<langsyntaxhighlight lang="java">
 
import java.util.Arrays;
Line 3,164:
return number == 1;
}
}</langsyntaxhighlight>
Output:
<pre>1
Line 3,179:
===ES5===
====Iteration====
<langsyntaxhighlight lang="javascript">function happy(number) {
var m, digit ;
var cycle = [] ;
Line 3,204:
document.write(number + " ") ;
number++ ;
}</langsyntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 3,211:
====Functional composition====
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// isHappy :: Int -> Bool
Line 3,270:
take(8, filter(isHappy, enumFromTo(1, 50)))
);
})()</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
Or, to stop immediately at the 8th member of the series, we can preserve functional composition while using an iteratively implemented '''until()''' function:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
 
// isHappy :: Int -> Bool
Line 3,345:
.xs
);
})();</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def is_happy_number:
def next: tostring | explode | map( (. - 48) | .*.) | add;
def last(g): reduce g as $i (null; $i);
Line 3,365:
end
end );
1 == last( [.,{}] | loop );</langsyntaxhighlight>
'''Emit a stream of the first n happy numbers''':
<langsyntaxhighlight lang="jq"># Set n to -1 to continue indefinitely:
def happy(n):
def subtask: # state: [i, found]
Line 3,378:
[0,0] | subtask;
 
happy($n|tonumber)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq --arg n 8 -n -f happy.jq
1
7
Line 3,389:
28
31
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
function happy(x)
happy_ints = ref(Int)
Line 3,407:
end
return happy_ints
end</langsyntaxhighlight>
Output
<pre> julia> happy(8)
Line 3,420:
31</pre>
A recursive version:
<langsyntaxhighlight lang="julia">sumhappy(n) = sum(x->x^2, digits(n))
 
function ishappy(x, mem = [])
Line 3,431:
 
happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-1]]
</syntaxhighlight>
</lang>
{{Out}}
<pre>julia> show(happy(8))
Line 3,439:
Faster with use of cache
{{trans|C}}
<langsyntaxhighlight lang="julia">const CACHE = 256
buf = zeros(Int,CACHE)
buf[1] = 1
Line 3,468:
end
return i-1
end</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> hpy: {x@&1={~|/x=1 4}{_+/_sqr 0$'$x}//:x}
 
hpy 1+!100
Line 3,477:
 
8#hpy 1+!100
1 7 10 13 19 23 28 31</langsyntaxhighlight>
 
Another implementation which is easy to follow is given below:
<syntaxhighlight lang="k">
<lang K>
/ happynum.k
 
Line 3,490:
hnum: {[x]; h::();i:1;while[(#h)<x; :[(isHappy i); h::(h,i)]; i+:1]; `0: ,"List of ", ($x), " Happy Numbers"; h}
 
</syntaxhighlight>
</lang>
 
The output of a session with this implementation is given below:
Line 3,505:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">// version 1.0.5-2
 
fun isHappy(n: Int): Boolean {
Line 3,534:
}
println("First 8 happy numbers : " + happyNums.joinToString(", "))
}</langsyntaxhighlight>
 
{{out}}
Line 3,542:
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">#!/usr/bin/lasso9
define isHappy(n::integer) => {
Line 3,556:
where isHappy(#x)
take 8
select #x</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="lasso">1, 7, 10, 13, 19, 23, 28, 31</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> ct = 0
n = 0
DO
Line 3,588:
sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
HappyN = HappyN(sqrInts, sqrInts$)
END FUNCTION</langsyntaxhighlight>
Output:-
<pre>1 1
Line 3,602:
=={{header|Locomotive Basic}}==
 
<langsyntaxhighlight lang="locobasic">10 mode 1:defint a-z
20 for i=1 to 100
30 i2=i
Line 3,617:
140 ' check if we have reached 8 numbers yet
150 if n=8 then end
160 next i</langsyntaxhighlight>
 
[[File:Happy Numbers, Locomotive BASIC.png]]
Line 3,623:
=={{header|Logo}}==
 
<langsyntaxhighlight lang="logo">to sum_of_square_digits :number
output (apply "sum (map [[d] d*d] ` :number))
end
Line 3,646:
 
print n_happy 8
bye</langsyntaxhighlight>
 
Output:
Line 3,654:
{{works with|lci 0.10.3}}
 
<langsyntaxhighlight lang="lolcode">OBTW
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
Line 3,736:
OIC
IM OUTTA YR LOOP
KTHXBYE</langsyntaxhighlight>
 
Output:<pre>1
Line 3,748:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function digits(n)
if n > 0 then return n % 10, digits(math.floor(n/10)) end
end
Line 3,762:
repeat
i, j = happy[j] and (print(j) or i+1) or i, j + 1
until i == 8</langsyntaxhighlight>
Output:
<pre>1
Line 3,779:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
Line 3,812:
PrintHappy=factoryHappy()
Call PrintHappy()
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,826:
=={{header|MAD}}==
 
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
BOOLEAN CYCLE
DIMENSION CYCLE(200)
Line 3,854:
END OF PROGRAM
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,869:
=={{header|Maple}}==
To begin, here is a procedure to compute the sum of the squares of the digits of a positive integer. It uses the built-in procedure irem, which computes the integer remainder and, if passed a name as the optional third argument, assigns it the corresponding quotient. (In other words, it performs integer division with remainder. There is also a dual, companion procedure iquo, which returns the integer quotient and assigns the remainder to the (optional) third argument.)
<langsyntaxhighlight Maplelang="maple">SumSqDigits := proc( n :: posint )
local s := 0;
local m := n;
Line 3,876:
end do;
s
end proc:</langsyntaxhighlight>
(Note that the unevaluation quotes on the third argument to irem are essential here, as that argument must be a name and, if m were passed without quotes, it would evaluate to a number.)
 
For example,
<syntaxhighlight lang="maple">
<lang Maple>
> SumSqDigits( 1234567890987654321 );
570
</syntaxhighlight>
</lang>
We can check this by computing it another way (more directly).
<syntaxhighlight lang="maple">
<lang Maple>
> n := 1234567890987654321:
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
570
</syntaxhighlight>
</lang>
The most straight-forward way to check whether a number is happy or sad seems also to be the fastest (that I could think of).
<langsyntaxhighlight Maplelang="maple">Happy? := proc( n )
if n = 1 then
true
Line 3,903:
evalb( s = 1 )
end if
end proc:</langsyntaxhighlight>
We can use this to determine the number of happy (H) and sad (S) numbers up to one million as follows.
<syntaxhighlight lang="maple">
<lang Maple>
> H, S := selectremove( Happy?, [seq]( 1 .. N ) ):
> nops( H ), nops( S );
143071, 856929
</syntaxhighlight>
</lang>
Finally, to solve the stated problem, here is a completely straight-forward routine to locate the first N happy numbers, returning them in a set.
<langsyntaxhighlight Maplelang="maple">FindHappiness := proc( N )
local count := 0;
local T := table();
Line 3,921:
end do;
{seq}( T[ i ], i = 1 .. count )
end proc:</langsyntaxhighlight>
With input equal to 8, we get
<syntaxhighlight lang="maple">
<lang Maple>
> FindHappiness( 8 );
{1, 7, 10, 13, 19, 23, 28, 31}
</syntaxhighlight>
</lang>
For completeness, here is an implementation of the cycle detection algorithm for recognizing happy numbers. It is much slower, however.
<langsyntaxhighlight Maplelang="maple">Happy? := proc( n :: posint )
local a, b;
a, b := n, SumSqDigits( n );
Line 3,936:
end do;
evalb( a = 1 )
end proc:</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Custom function HappyQ:
<langsyntaxhighlight Mathematicalang="mathematica">AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]]
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1</langsyntaxhighlight>
Examples for a specific number:
<langsyntaxhighlight Mathematicalang="mathematica">HappyQ[1337]
HappyQ[137]</langsyntaxhighlight>
gives back:
<syntaxhighlight lang="mathematica">True
<lang Mathematica>True
False</langsyntaxhighlight>
Example finding the first 8:
<langsyntaxhighlight Mathematicalang="mathematica">m = 8;
n = 1;
i = 0;
Line 3,961:
]
]
happynumbers</langsyntaxhighlight>
gives back:
<langsyntaxhighlight Mathematicalang="mathematica">{1, 7, 10, 13, 19, 23, 28, 31}</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Recursive version:
<langsyntaxhighlight MATLABlang="matlab">function findHappyNumbers
nHappy = 0;
k = 1;
Line 3,988:
hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]);
end
end</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31 </pre>
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
fn isHappyNumber n =
(
Line 4,020:
)
</syntaxhighlight>
</lang>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
1
7
Line 4,031:
28
31
</syntaxhighlight>
</lang>
 
=={{header|Mercury}}==
<langsyntaxhighlight Mercurylang="mercury">:- module happy.
:- interface.
:- import_module io.
Line 4,073:
:- func sqr(int) = int.
 
sqr(X) = X * X.</langsyntaxhighlight>
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 4,079:
=={{header|MiniScript}}==
This solution uses the observation that any infinite cycle of this algorithm hits the number 89, and so that can be used to know when we've found an unhappy number.
<langsyntaxhighlight MiniScriptlang="miniscript">isHappy = function(x)
while true
if x == 89 then return false
Line 4,098:
i = i + 1
end while
print "First 8 happy numbers: " + found</langsyntaxhighlight>
{{out}}
<pre>First 8 happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 4,104:
=={{header|ML}}==
==={{header|mLite}}===
<langsyntaxhighlight lang="ocaml">(*
A happy number is defined by the following process. Starting with any positive integer, replace the number
by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will
Line 4,139:
 
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
</syntaxhighlight>
</lang>
Output:
<pre>1 is happy
Line 4,153:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE HappyNumbers;
FROM InOut IMPORT WriteCard, WriteLn;
 
Line 4,196:
INC(num);
END;
END HappyNumbers.</langsyntaxhighlight>
{{out}}
<pre> 1
Line 4,208:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">ISHAPPY(N)
;Determines if a number N is a happy number
;Note that the returned strings do not have a leading digit unless it is a happy number
Line 4,231:
FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
KILL I
QUIT</langsyntaxhighlight>
Output:<pre>
USER>D HAPPY^ROSETTA(8)
Line 4,253:
=={{header|NetRexx}}==
{{trans|REXX}}
<langsyntaxhighlight lang="netrexx">/*NetRexx program to display the 1st 8 (or specified arg) happy numbers*/
limit = arg[0] /*get argument for LIMIT. */
say limit
Line 4,280:
q=sum /*now, lets try the Q sum. */
end
end</langsyntaxhighlight>
;Output
<pre>
Line 4,398:
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import intsets
 
proc happy(n: int): bool =
Line 4,417:
for x in 0..31:
if happy(x):
echo x</langsyntaxhighlight>
Output:
<pre>1
Line 4,429:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">use IO;
use Structure;
 
Line 4,475:
}
}
}</langsyntaxhighlight>
output:
<pre>First 8 happy numbers: 1,7,10,13,19,23,28,31,</pre>
Line 4,481:
=={{header|OCaml}}==
Using [[wp:Cycle detection|Floyd's cycle-finding algorithm]].
<langsyntaxhighlight lang="ocaml">open Num
 
let step =
Line 4,505:
 
List.iter print_endline (
List.rev_map string_of_num (first 8)) ;;</langsyntaxhighlight>
Output:
<pre>$ ocaml nums.cma happy_numbers.ml
Line 4,519:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: isHappy(n)
| cycle |
ListBuffer new ->cycle
Line 4,534:
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;</langsyntaxhighlight>
 
Output:
Line 4,543:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
count = 0
say "First 8 happy numbers are:"
Line 4,572:
number = next
end
</syntaxhighlight>
</lang>
<pre>
First 8 happy numbers are:
Line 4,586:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">functor
import
System
Line 4,629:
in
{System.show {List.take HappyNumbers 8}}
end</langsyntaxhighlight>
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Line 4,636:
{{PARI/GP select}}
If the number has more than three digits, the sum of the squares of its digits has fewer digits than the number itself. If the number has three digits, the sum of the squares of its digits is at most 3 * 9^2 = 243. A simple solution is to look up numbers up to 243 and calculate the sum of squares only for larger numbers.
<langsyntaxhighlight lang="parigp">H=[1,7,10,13,19,23,28,31,32,44,49,68,70,79,82,86,91,94,97,100,103,109,129,130,133,139,167,176,188,190,192,193,203,208,219,226,230,236,239];
isHappy(n)={
if(n<262,
Line 4,645:
)
};
select(isHappy, vector(31,i,i))</langsyntaxhighlight>
Output:
<pre>%1 = [1, 7, 10, 13, 19, 23, 28, 31]</pre>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program HappyNumbers (output);
 
uses
Line 4,710:
end;
writeln;
end.</langsyntaxhighlight>
Output:
<pre>:> ./HappyNumbers
Line 4,721:
Extended to 10e18
Tested with Free Pascal 3.0.4
<langsyntaxhighlight lang="pascal">Program HappyNumbers (output);
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,970:
writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0));
end.
</syntaxhighlight>
</lang>
;output:
<pre>
Line 5,022:
=={{header|Perl}}==
Since all recurrences end with 1 or repeat (37,58,89,145,42,20,4,16), we can do this test very quickly without having to make hashes of seen numbers.
<langsyntaxhighlight lang="perl">use List::Util qw(sum);
 
sub ishappy {
Line 5,033:
 
my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n";</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,039:
Or we can solve using only the rudimentary task knowledge as below. Note the slightly different ways of doing the digit sum and finding the first 8 numbers where ishappy(n) is true -- this shows there's more than one way to do even these small sub-tasks.
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use List::Util qw(sum);
sub is_happy {
my ($n) = @_;
Line 5,051:
 
my $n;
is_happy( ++$n ) and print "$n " or redo for 1..8;</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,057:
=={{header|Phix}}==
Copy of [[Happy_numbers#Euphoria|Euphoria]] tweaked to give a one-line output
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">is_happy</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">seen</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 5,084:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,092:
=={{header|PHP}}==
{{trans|D}}
<langsyntaxhighlight lang="php">function isHappy($n) {
while (1) {
$total = 0;
Line 5,115:
}
$i++;
}</langsyntaxhighlight>
<pre>1 7 10 13 19 23 28 31 </pre>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
println(happy_len(8)).
 
Line 5,143:
end,
N := N + 1
end.</langsyntaxhighlight>
 
{{out}}
Line 5,149:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de happy? (N)
(let Seen NIL
(loop
Line 5,161:
(do 8
(until (happy? (inc 'H)))
(printsp H) ) )</langsyntaxhighlight>
Output:
<pre>1 7 10 13 19 23 28 31</pre>
 
=={{header|PILOT}}==
<langsyntaxhighlight lang="pilot">C :max=8
:n=0
:i=0
Line 5,202:
:x=y
J (x):*digit
E :</langsyntaxhighlight>
{{out}}
<pre>1
Line 5,214:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">test: proc options (main); /* 19 November 2011 */
declare (i, j, n, m, nh initial (0) ) fixed binary (31);
 
Line 5,238:
end;
end test;
</syntaxhighlight>
</lang>
OUTPUT:
<pre>
Line 5,252:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
 
/* FIND SUM OF SQUARE OF DIGITS OF NUMBER */
Line 5,322:
 
CALL BDOS(0,0);
EOF</langsyntaxhighlight>
{{out}}
<pre>1
Line 5,334:
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">sqr = (n): n * n.
 
isHappy = (n) :
Line 5,353:
if (isHappy(i)): firstEight append(i).
.
firstEight string print</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">function happy([int] $n) {
$a=@()
for($i=2;$a.count -lt $n;$i++) {
Line 5,375:
}
$a -join ','
}</langsyntaxhighlight>
Output :
<langsyntaxhighlight PowerShelllang="powershell">happy(8)
7,10,13,19,23,28,31,32</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<langsyntaxhighlight Prologlang="prolog">happy_numbers(L, Nb) :-
% creation of the list
length(L, Nb),
Line 5,428:
 
square(N, SN) :-
SN is N * N.</langsyntaxhighlight>
Output :
<langsyntaxhighlight Prologlang="prolog"> ?- happy_numbers(L, 8).
L = [1,7,10,13,19,23,28,31].</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#ToFind=8
#MaxTests=100
#True = 1: #False = 0
Line 5,467:
Until i>#MaxTests
ProcedureReturn #False
EndProcedure</langsyntaxhighlight>
Sample output:
<pre>#1 1
Line 5,480:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">>>> def happy(n):
past = set()
while n != 1:
Line 5,490:
 
>>> [x for x in xrange(500) if happy(x)][:8]
[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
===Composition of pure functions===
 
Drawing 8 terms from a non finite stream, rather than assuming prior knowledge of the finite sample size required:
<langsyntaxhighlight lang="python">'''Happy numbers'''
 
from itertools import islice
Line 5,573:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 5,579:
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">
<lang Quackery>
[ 0 swap
[ 10 /mod 2 **
Line 5,601:
drop nip ] is happies ( n --> [ )
 
8 happies echo</langsyntaxhighlight>
 
{{Out}}
Line 5,608:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">is.happy <- function(n)
{
stopifnot(is.numeric(n) && length(n)==1)
Line 5,636:
}
happy
}</langsyntaxhighlight>
Example usage
<syntaxhighlight lang R="r">is.happy(2)</langsyntaxhighlight>
[1] FALSE
attr(,"cycle")
[1] 4 16 37 58 89 145 42 20
<langsyntaxhighlight Rlang="r">#Find happy numbers between 1 and 50
which(apply(rbind(1:50), 2, is.happy))</langsyntaxhighlight>
1 7 10 13 19 23 28 31 32 44 49
<langsyntaxhighlight Rlang="r">#Find the first 8 happy numbers
happies <- c()
i <- 1L
Line 5,653:
i <- i + 1L
}
happies</langsyntaxhighlight>
1 7 10 13 19 23 28 31
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
Line 5,678:
x))
 
(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-13}}
<syntaxhighlight lang="raku" perl6line>sub happy (Int $n is copy --> Bool) {
loop {
state %seen;
Line 5,692:
}
 
say join ' ', grep(&happy, 1 .. *)[^8];</langsyntaxhighlight>
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Here's another approach that uses a different set of tricks including lazy lists, gather/take, repeat-until, and the cross metaoperator X.
<syntaxhighlight lang="raku" perl6line>my @happy = lazy gather for 1..* -> $number {
my %stopper = 1 => 1;
my $n = $number;
Line 5,705:
}
 
say ~@happy[^8];</langsyntaxhighlight>
Output is the same as above.
 
Here is a version using a subset and an anonymous recursion (we cheat a little bit by using the knowledge that 7 is the second happy number):
<syntaxhighlight lang="raku" perl6line>subset Happy of Int where sub ($n) {
$n == 1 ?? True !!
$n < 7 ?? False !!
Line 5,715:
}
say (grep Happy, 1 .. *)[^8];</langsyntaxhighlight>
Again, output is the same as above. It is not clear whether this version returns in finite time for any integer, though.
 
Line 5,721:
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
<lang Relation>
function happy(x)
set y = x
Line 5,753:
set i = i + 1
end while
</syntaxhighlight>
</lang>
 
<pre>
Line 5,768:
=={{header|REXX}}==
===unoptimized===
<langsyntaxhighlight REXXlang="rexx">/*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.*/
Line 5,786:
haps=haps+1 /*bump the count of happy numbers. */
end /*n*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 8 </tt>}}
<pre>
Line 5,804:
<br><br>This REXX version also accepts a &nbsp; ''range'' &nbsp; of happy numbers to be shown, &nbsp; that is,
<br>it can show the 2000<sup>th</sup> through the 2032<sup>nd</sup> (inclusive) happy numbers &nbsp; (as shown below).
<langsyntaxhighlight lang="rexx">/*REXX program computes and displays a specified range of happy numbers. */
parse arg L H . /*obtain optional arguments from the CL*/
if L=='' | L=="," then L=8 /*Not specified? Then use the default.*/
Line 5,830:
say right(n, 30) /*display right justified happy number.*/
end /*n*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 2000 &nbsp; 2032 </tt>}}
<pre>
Line 5,870:
===optimized, horizontal list===
This REXX version is identical to the optimized version, &nbsp; but displays the numbers in a horizontal list.
<langsyntaxhighlight lang="rexx">/*REXX program computes and displays a specified range of happy numbers. */
sw=linesize() - 1 /*obtain the screen width (less one). */
parse arg limit . /*obtain optional argument from the CL.*/
Line 5,903:
end /*n*/
if $\='' then say strip($) /*display any residual happy numbers. */
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
This REXX program makes use of &nbsp; '''linesize''' &nbsp; REXX program (or BIF) which is used to determine the screen width (or linesize) of the terminal (console).
 
Line 5,957:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">n = 1
found = 0
Line 5,981:
End
Return True
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,997:
{{works with|Ruby|2.1}}
 
<langsyntaxhighlight lang="ruby">require 'set' # Set: Fast array lookup / Simple existence hash
 
@seen_numbers = Set.new
Line 6,015:
false # Return false
end
end</langsyntaxhighlight>
 
Helper method to produce output:
<langsyntaxhighlight lang="ruby">def print_happy
happy_numbers = []
 
Line 6,029:
end
 
print_happy</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="ruby">[1, 7, 10, 13, 19, 23, 28, 31]</langsyntaxhighlight>
 
===Alternative version===
<langsyntaxhighlight lang="ruby">@memo = [0,1]
def happy(n)
sum = n.to_s.chars.map{|c| c.to_i**2}.inject(:+)
Line 6,052:
for i in 99999999999900..99999999999999
puts i if happy(i)==1
end</langsyntaxhighlight>
 
{{out}}
Line 6,081:
===Simpler Alternative===
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def happy?(n)
past = []
until n == 1
Line 6,094:
until count == 8; puts i or count += 1 if happy?(i += 1) end
puts
(99999999999900..99999999999999).each { |i| puts i if happy?(i) }</langsyntaxhighlight>
{{out}}
<pre>
Line 6,120:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1 to 100
if happy(i) = 1 then
cnt = cnt + 1
Line 6,138:
num = happy
wend
end function</langsyntaxhighlight>
<pre>1. 1 is a happy number
2. 7 is a happy number
Line 6,151:
=={{header|Rust}}==
In Rust, using a tortoise/hare cycle detection algorithm (generic for integer types)
<langsyntaxhighlight lang="rust">#![feature(core)]
 
fn sumsqd(mut n: i32) -> i32 {
Line 6,186:
 
println!("{:?}", happy)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,193:
 
=={{header|Salmon}}==
<langsyntaxhighlight Salmonlang="salmon">variable happy_count := 0;
outer:
iterate(x; [1...+oo])
Line 6,221:
now := new;
};
};</langsyntaxhighlight>
This Salmon program produces the following output:
<pre>1 is happy.
Line 6,233:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">scala> def isHappy(n: Int) = {
| new Iterator[Int] {
| val seen = scala.collection.mutable.Set[Int]()
Line 6,257:
28
31
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (number->list num)
(do ((num num (quotient num 10))
(lst '() (cons (remainder num 10) lst)))
Line 6,276:
(cond ((= more 0) (newline))
((happy? n) (display " ") (display n) (loop (+ n 1) (- more 1)))
(else (loop (+ n 1) more))))</langsyntaxhighlight>
The output is:
<pre>happy numbers: 1 7 10 13 19 23 28 31</pre>
Line 6,288:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: cacheType is hash [integer] boolean;
Line 6,329:
end if;
end for;
end func;</langsyntaxhighlight>
 
Output:
Line 6,347:
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang="sequencel">import <Utilities/Math.sl>;
import <Utilities/Conversion.sl>;
 
Line 6,373:
true when n = 1
else
isHappyHelper(newN, cache ++ [n]);</langsyntaxhighlight>
 
{{out}}
Line 6,382:
 
=={{header|SETL}}==
<langsyntaxhighlight SETLlang="setl">proc is_happy(n);
s := [n];
while n > 1 loop
Line 6,391:
end while;
return true;
end proc;</langsyntaxhighlight>
<langsyntaxhighlight SETLlang="setl">happy := [];
n := 1;
until #happy = 8 loop
Line 6,399:
end loop;
 
print(happy);</langsyntaxhighlight>
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Alternative version:
<langsyntaxhighlight SETLlang="setl">print([n : n in [1..100] | is_happy(n)](1..8));</langsyntaxhighlight>
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func happy(n) is cached {
static seen = Hash()
 
Line 6,418:
}
 
say happy.first(8)</langsyntaxhighlight>
 
{{out}}
Line 6,429:
{{trans|Python}}
In addition to the "Python's cache mechanism", the use of a Bag assures that found e.g. the happy 190, we already have in cache also the happy 910 and 109, and so on.
<langsyntaxhighlight lang="smalltalk">Object subclass: HappyNumber [
|cache negativeCache|
HappyNumber class >> new [ |me|
Line 6,491:
]
]
].</langsyntaxhighlight>
<langsyntaxhighlight lang="smalltalk">|happy|
happy := HappyNumber new.
 
Line 6,498:
(happy isHappy: i)
ifTrue: [ i displayNl ]
].</langsyntaxhighlight>
Output:
1
Line 6,511:
an alternative version is:
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|next isHappy happyNumbers|
 
next :=
Line 6,535:
try := try + 1
].
happyNumbers printCR</langsyntaxhighlight>
Output:
OrderedCollection(1 7 10 13 19 23 28 31)
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func isHappyNumber(var n:Int) -> Bool {
var cycle = [Int]()
Line 6,564:
}
count++
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,578:
=={{header|Tcl}}==
using code from [[Sum of squares#Tcl]]
<langsyntaxhighlight lang="tcl">proc is_happy n {
set seen [list]
while {$n > 1 && [lsearch -exact $seen $n] == -1} {
Line 6,593:
incr n
}
puts "the first 8 happy numbers are: [list $happy]"</langsyntaxhighlight>
<pre>the first 8 happy numbers are: {1 7 10 13 19 23 28 31}</pre>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
SECTION check
IF (n!=1) THEN
Line 6,632:
DO check
ENDLOOP
ENDLOOP</langsyntaxhighlight>
Output:
<pre>
Line 6,646:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">
' ************************
' MAIN
Line 6,709:
' END SUBS & FUNCTIONS
' ************************
</syntaxhighlight>
</lang>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
<langsyntaxhighlight lang="bash">#!/bin/bash
function sum_of_square_digits
{
Line 6,752:
}
 
first_n_happy 8</langsyntaxhighlight>
Output:<pre>1
7
Line 6,766:
and first(p) defines a function mapping a number n to the first n
positive naturals having property p.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 6,775:
#cast %nL
 
main = (first happy) 8</langsyntaxhighlight>
output:
<pre><1,7,10,13,19,23,28,31></pre>
Line 6,781:
=={{header|Vala}}==
{{libheader|Gee}}
<langsyntaxhighlight lang="vala">using Gee;
 
/* function to sum the square of the digits */
Line 6,826:
stdout.printf("%d ", num);
stdout.printf("\n");
} // end main</langsyntaxhighlight>
The output is:
<pre>
Line 6,834:
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 6,864:
Is_Happy_Number = True
End Function
</syntaxhighlight>
</lang>
{{Out}}
<pre>Is Happy : 1
Line 6,876:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
count = 0
firsteigth=""
Line 6,907:
Loop
End Function
</syntaxhighlight>
</lang>
 
{{Out}}
Line 6,914:
=={{header|Visual Basic .NET}}==
This version uses Linq to carry out the calculations.
<langsyntaxhighlight lang="vbnet">Module HappyNumbers
Sub Main()
Dim n As Integer = 1
Line 6,942:
Return True
End Function
End Module</langsyntaxhighlight>
The output is:
<pre>1: 1
Line 6,955:
{{trans|C#}}
Curiously, this runs in about two thirds of the time of the cacheless C# version on Tio.run.
<langsyntaxhighlight lang="vbnet">Module Module1
 
Dim sq As Integer() = {1, 4, 9, 16, 25, 36, 49, 64, 81}
Line 6,994:
Console.WriteLine(vbLf & "Computation time {0} seconds.", (DateTime.Now - st).TotalSeconds)
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>---Happy Numbers---
Line 7,009:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">fn happy(h int) bool {
mut m := map[int]bool{}
mut n := h
Line 7,034:
}
println('')
}</langsyntaxhighlight>
{{out}}
<pre>
Line 7,042:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight lang="ecmascript">var happy = Fn.new { |n|
var m = {}
while (n > 1) {
Line 7,067:
n = n + 1
}
System.print()</langsyntaxhighlight>
 
{{out}}
Line 7,081:
numbers.
 
<langsyntaxhighlight XPL0lang="xpl0">int List(810); \list of numbers in a cycle
int Inx; \index for List
include c:\cxpl\codes;
Line 7,125:
N0:= N0+1; \next starting number
until C=8; \done when 8 happy numbers have been found
]</langsyntaxhighlight>
 
Output:
Line 7,140:
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
Line 7,177:
return s;
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 7,185:
Here is a function that generates a continuous stream of happy numbers. Given that there are lots of happy numbers, caching them doesn't seem like a good idea memory wise. Instead, a num of squared digits == 4 is used as a proxy for a cycle (see the Wikipedia article, there are several number that will work).
{{trans|Icon and Unicon}}
<langsyntaxhighlight lang="zkl">fcn happyNumbers{ // continously spew happy numbers
foreach N in ([1..]){
n:=N; while(1){
Line 7,193:
}
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">h:=Utils.Generator(happyNumbers);
h.walk(8).println();</langsyntaxhighlight>
{{out}}
<pre>L(1,7,10,13,19,23,28,31)</pre>
Get the one million-th happy number. Nobody would call this quick.
<langsyntaxhighlight lang="zkl">Utils.Generator(happyNumbers).drop(0d1_000_000-1).next().println();</langsyntaxhighlight>
{{out}}<pre>7105849</pre>
 
=={{header|ZX Spectrum Basic}}==
{{trans|Run_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 FOR i=1 TO 100
20 GO SUB 1000
30 IF isHappy=1 THEN PRINT i;" is a happy number"
Line 7,219:
1080 NEXT j
1090 LET num=isHappy
1100 GO TO 1020</langsyntaxhighlight>
10,327

edits