Happy numbers: Difference between revisions
m
syntax highlighting fixup automation
(Applesoft BASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 24:
{{trans|Python}}
<
Set[Int] past
L n != 1
Line 33:
R 1B
print((0.<500).filter(x -> happy(x))[0.<8])</
{{out}}
Line 52:
under 256, the cycle never goes above 163; this program could be trivially changed to print up to 39 happy numbers.
<
puts: equ 9 ; CP/M print string
bdos: equ 5 ; CP/M entry point
Line 128:
adi 10
ret ; 1s digit is left in A afterwards
string: db '000',13,10,'$'</
{{out}}
Line 143:
=={{header|8th}}==
<
: until! "not while!" eval i;
Line 173:
;with
;with
</syntaxhighlight>
{{out}}
<pre>
Line 181:
=={{header|ACL2}}==
<
(defun sum-of-digit-squares (n)
Line 205:
(defun first-happy-nums (n)
(first-happy-nums-r n 1))</
Output:
<pre>(1 7 10 13 19 23 28 31)</pre>
=={{header|Action!}}==
<
BYTE sum,d
Line 260:
x==+1
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Happy_numbers.png Screenshot from Atari 8-bit computer]
Line 275:
=={{header|ActionScript}}==
<
{
var sum:uint = 0;
Line 316:
}
}
printHappy();</
Sample output:
<pre>
Line 330:
=={{header|Ada}}==
<
with Ada.Containers.Ordered_Sets;
Line 370:
end if;
end loop;
end Test_Happy_Digits;</
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}}
<
PROC next = (INT in n)INT: (
Line 404:
print((i, new line))
FI
OD</
Output:
<pre>
Line 418:
=={{header|ALGOL-M}}==
<
integer function mod(a,b);
integer a,b;
Line 455:
i := i + 1;
end;
end</
{{out}}
<pre> 1
Line 467:
=={{header|ALGOL W}}==
<
% 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.</
{{out}}
<pre>
Line 529:
===Tradfn===
<
[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
∇</
<pre>
HappyNumbers 100 8
Line 555:
===Dfn===
<syntaxhighlight lang="apl">
HappyNumbers←{ ⍝ return the first ⍵ Happy Numbers
⍺←⍬ ⍝ initial list
Line 570:
HappyNumbers 8
1 7 10 13 19 23 28 31
</syntaxhighlight>
=={{header|AppleScript}}==
===Iteration===
<
set howManyHappyNumbers to 8
set happyNumberList to {}
Line 606:
end repeat
return (numberToCheck = 1)
end isHappy</
<pre>
Result: (*1, 7, 10, 13, 19, 23, 28, 31*)
Line 614:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<
-- isHappy :: Int -> Bool
Line 740:
end tell
return v
end |until|</
{{Out}}
<
=={{header|Applesoft BASIC}}==
<
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</
{{out}}
<pre>
Line 761:
{{trans|Nim}}
<
happy?: function [x][
n: x
Line 781:
loop 0..31 'x [
if happy? x -> print x
]</
{{out}}
Line 795:
=={{header|AutoHotkey}}==
<
If isHappy(A_Index) {
out .= (out="" ? "" : ",") . A_Index
Line 815:
Return false
Else Return isHappy(sum, list)
}</
<pre>
The first 8 happy numbers are: 1,7,10,13,19,23,28,31
</pre>
===Alternative version===
<
if (Happy(A_Index)) {
Out .= A_Index A_Space
Line 837:
n := t, t := 0
}
}</
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|AutoIt}}==
<
$c = 0
$k = 0
Line 864:
EndIf
WEnd
</syntaxhighlight>
<pre>
Line 880:
===Alternative version===
<
$c = 0
$k = 0
Line 905:
$a.Clear
WEnd
</syntaxhighlight>
<pre>
Saves all numbers in a list, duplicate entry indicates a loop.
Line 920:
=={{header|AWK}}==
<
{
if ( n in happy ) return 1;
Line 960:
}
}
}</
Result:
<pre>1
Line 975:
Alternately, for legibility one might write:
<
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
Line 1,002:
}
return tot
}</
=={{header|BASIC256}}==
<
print "The first 8 isHappy numbers are:"
print
Line 1,029:
num = isHappy
end while
end function</
=={{header|Batch File}}==
happy.bat
<
setlocal enableDelayedExpansion
::Define a list with 10 terms as a convenience for defining a loop
Line 1,113:
)
set /a n=sum
)</
Sample usage and output
<pre>
Line 1,173:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
total% = 0
REPEAT
Line 1,193:
num% = MOD(digit&())^2 + 0.5
UNTIL num% = 1 OR num% = 4
= (num% = 1)</
Output:
<pre> 1 is a happy number
Line 1,205:
=={{header|BCPL}}==
<
let sumdigitsq(n) =
Line 1,229:
$)
wrch('*N')
$)</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Bori}}==
<
{
ints cache;
Line 1,269:
}
puts("First 8 happy numbers : " + str.newline + happynums);
}</
Output:
<pre>First 8 happy numbers :
Line 1,275:
=={{header|BQN}}==
<
Happy ← ⟨⟩{𝕨((⊑∊˜ )◶⟨∾𝕊(SumSqDgt⊢),1=⊢⟩)𝕩}⊢
8↑Happy¨⊸/↕50</
{{out}}
<pre>⟨ 1 7 10 13 19 23 28 31 ⟩</pre>
=={{header|Brat}}==
<
happiness = set.new 1
Line 1,310:
p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"</
Output:
<pre>First eight happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]
Line 1,318:
=={{header|C}}==
Recursively look up if digit square sum is happy.
<
#define CACHE 256
Line 1,350:
return 0;
}</
output<pre>1 7 10 13 19 23 28 31
The 1000000th happy number: 7105849</pre>
Without caching, using cycle detection:
<
int dsum(int n)
Line 1,384:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,435:
}
}
}</
<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).<
using System.Collections.Generic;
class Program
Line 1,475:
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}</
{{out}}
<pre>---Happy Numbers---
Line 1,490:
=={{header|C++}}==
{{trans|Python}}
<
#include <set>
Line 1,525:
std::cout << i << std::endl;
return 0;
}</
Output:
<pre>1
Line 1,539:
49</pre>
Alternative version without caching:
<
{
unsigned int result = 0;
Line 1,579:
}
std::cout << std::endl;
}</
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 1,585:
=={{header|Clojure}}==
<
(loop [n n, seen #{}]
(cond
Line 1,599:
(def happy-numbers (filter happy? (iterate inc 1)))
(println (take 8 happy-numbers))</
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
===Alternate Version (with caching)===
<
(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})})
Line 1,636:
(filter #(= :happy (happy-algo %)))))
(println (take 8 happy-numbers))</
Same output.
=={{header|CLU}}==
<
sum_sq: int := 0
while n > 0 do
Line 1,675:
stream$putl(po, int$unparse(i))
end
end start_up </
{{out}}
<pre>1
Line 1,687:
=={{header|CoffeeScript}}==
<
seen = {}
while true
Line 1,708:
console.log i
cnt += 1
i += 1</
output
<pre>
Line 1,723:
=={{header|Common Lisp}}==
<
(* n n))
Line 1,744:
(print (happys))
</syntaxhighlight>
Output:<pre>(1 7 10 13 19 23 28 31)</pre>
=={{header|Cowgol}}==
<
sub sumDigitSquare(n: uint8): (s: uint8) is
Line 1,786:
end if;
n := n + 1;
end loop;</
{{out}}
Line 1,801:
=={{header|Crystal}}==
{{trans|Ruby}}
<
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) }</
{{out}}
<pre>
Line 1,840:
=={{header|D}}==
<
int[int] past;
Line 1,862:
int.max.iota.filter!isHappy.take(8).writeln;
}</
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
===Alternative Version===
<
bool isHappy(int n) pure nothrow {
Line 1,884:
void main() {
int.max.iota.filter!isHappy.take(8).writeln;
}</
Same output.
=={{header|Dart}}==
<
HashMap<int,bool> happy=new HashMap<int,bool>();
happy[1]=true;
Line 1,922:
i++;
}
}</
=={{header|dc}}==
<
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx</
Output:
<pre>1
Line 1,940:
=={{header|DCL}}==
<
$ found = 0
$ i = 1
Line 1,989:
$ goto loop1
$ done:
$ show symbol found*</
{{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">
program Happy_numbers;
Line 2,068:
writeln;
readln;
end.</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|Draco}}==
<
byte r, d;
r := 0;
Line 2,105:
n := n + 1
od
corp</
{{out}}
<pre> 1
Line 2,117:
=={{header|DWScript}}==
<
var
cache : array of Integer;
Line 2,146:
Dec(n);
end;
end;</
Output:
<pre>1
Line 2,159:
=={{header|Dyalect}}==
<
var m = []
while n > 1 {
Line 2,185:
n += 1
}
print()</
{{out}}
Line 2,192:
=={{header|Déjà Vu}}==
<
0
while over:
Line 2,228:
++
drop
drop</
{{output}}
<pre>A happy number: 1
Line 2,241:
=={{header|E}}==
{{output?|E}}
<
var seen := [].asSet()
while (!seen.contains(x)) {
Line 2,260:
println(x)
if ((count += 1) >= 8) { break }
}</
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 2,335:
end
</syntaxhighlight>
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<
import system'collections;
import system'routines;
Line 2,383:
};
console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}</
{{out}}
<pre>
Line 2,390:
=={{header|Elixir}}==
<
def task(num) do
Process.put({:happy, 1}, true)
Line 2,416:
end
IO.inspect Happy.task(8)</
{{out}}
Line 2,424:
=={{header|Erlang}}==
<
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
Line 2,456:
main() ->
main(0, []).
</syntaxhighlight>
Command: <
Output: <
In a more functional style (assumes integer_to_list/1 will convert to the ASCII value of a number, which then has to be converted to the integer value by subtracting 48):
<
-export([main/0]).
Line 2,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.</
Output:
<pre>[1,7,10,13,19,23,28,31]</pre>
=={{header|Euphoria}}==
<
sequence seen
integer k
Line 2,511:
end if
n += 1
end while</
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#
<
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>
Output:
<pre>
Line 2,568:
=={{header|Factor}}==
<
: squares ( n -- s )
Line 2,588:
dup happy? [ dup , [ 1 - ] dip ] when 1 +
] while 2drop
] { } make ;</
{{out}}
<
=={{header|FALSE}}==
<
[$m;![$9>][m;!@@+\]#$*+]s: {sum of squares}
[$0[1ø1>][1ø3+ø3ø=|\1-\]#\%]f: {look for duplicates}
Line 2,607:
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%</
{{out}}
Line 2,613:
=={{header|Fantom}}==
<
{
static Bool isHappy (Int n)
Line 2,648:
}
}
</syntaxhighlight>
Output:
<pre>
Line 2,662:
=={{header|FOCAL}}==
<
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</
{{out}}
Line 2,694:
=={{header|Forth}}==
<
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</
===Lookup Table===
Every sequence either ends in 1, or contains a 4 as part of a cycle. Extending the table through 9 is a (modest) optimization/memoization. This executes '500000 happy-numbers' about 5 times faster than the above solution.
<
: next ( n -- n')
0 swap BEGIN dup WHILE 10 /mod >r dup * + r> REPEAT drop ;
Line 2,726:
BEGIN 1+ dup happy? UNTIL dup . r> 1- >r
REPEAT r> drop drop ;
8 happy-numbers</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Produces the 1 millionth happy number with:
<
>r 0 BEGIN r@ WHILE
BEGIN 1+ dup happy? UNTIL r> 1- >r
REPEAT r> drop ;
1000000 happy-number . \ 7105849</
in about 9 seconds.
=={{header|Fortran}}==
<
implicit none
Line 2,804:
end function is_happy
end program happy</
Output:
<pre>1
Line 2,816:
=={{header|FreeBASIC}}==
<
Function isHappy(n As Integer) As Boolean
Line 2,859:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,878:
{{Works with|Frege|3.21.586-g026e8d7}}
<
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</
{{out}}
Line 2,912:
=={{header|Go}}==
<
import "fmt"
Line 2,940:
}
fmt.Println()
}</
{{out}}
<pre>
Line 2,947:
=={{header|Groovy}}==
<
def number = delegate as Long
def cycle = new HashSet<Long>()
Line 2,961:
if (i.happy) { matches << i }
}
println matches</
{{out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|Harbour}}==
<
LOCAL i := 8, nH := 0
Line 2,998:
AAdd( aUnhappy, nSum )
RETURN IsHappy( nSum )</
Output:
Line 3,005:
=={{header|Haskell}}==
<
import Data.Set (member, insert, empty)
Line 3,018:
main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]</
{{Out}}
<pre>1
Line 3,030:
We can create a cache for small numbers to greatly speed up the process:
<
happy :: Int -> Bool
Line 3,048:
main :: IO ()
main = print $ sum $ take 10000 $ filter happy [1 ..]</
{{Out}}
<pre>327604323</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
local n
n := arglist[1] | 8 # limiting number of happy numbers to generate, default=8
Line 3,069:
if happy(n) then return i
}
end</
Usage and Output:
<pre>
Line 3,078:
=={{header|J}}==
<
1 7 10 13 19 23 28 31</
This is a repeat while construction
<
that produces an array of 1's and 4's, which is converted to 1's and 0's forming a binary array having a 1 for a happy number. Finally the happy numbers are extracted by a binary selector.
<
So for easier reading the solution could be expressed as:
<
sumSqrDigits=: +/@(*:@(,.&.":))
Line 3,091:
14
8{. (#~ 1 = sumSqrDigits ^: cond ^:_ "0) 1 + i.100
1 7 10 13 19 23 28 31</
=={{header|Java}}==
{{works with|Java|1.5+}}
{{trans|JavaScript}}
<
public class Happy{
public static boolean happy(long number){
Line 3,122:
}
}
}</
Output:
<pre>1
Line 3,137:
{{works with|Java|1.8}}
{{trans|Java}}
<
import java.util.Arrays;
Line 3,164:
return number == 1;
}
}</
Output:
<pre>1
Line 3,179:
===ES5===
====Iteration====
<
var m, digit ;
var cycle = [] ;
Line 3,204:
document.write(number + " ") ;
number++ ;
}</
Output:
<pre>1 7 10 13 19 23 28 31 </pre>
Line 3,211:
====Functional composition====
{{Trans|Haskell}}
<
// isHappy :: Int -> Bool
Line 3,270:
take(8, filter(isHappy, enumFromTo(1, 50)))
);
})()</
{{Out}}
<
Or, to stop immediately at the 8th member of the series, we can preserve functional composition while using an iteratively implemented '''until()''' function:
<
// isHappy :: Int -> Bool
Line 3,345:
.xs
);
})();</
{{Out}}
<
=={{header|jq}}==
{{works with|jq|1.4}}
<
def next: tostring | explode | map( (. - 48) | .*.) | add;
def last(g): reduce g as $i (null; $i);
Line 3,365:
end
end );
1 == last( [.,{}] | loop );</
'''Emit a stream of the first n happy numbers''':
<
def happy(n):
def subtask: # state: [i, found]
Line 3,378:
[0,0] | subtask;
happy($n|tonumber)</
{{out}}
<
1
7
Line 3,389:
28
31
</syntaxhighlight>
=={{header|Julia}}==
<
function happy(x)
happy_ints = ref(Int)
Line 3,407:
end
return happy_ints
end</
Output
<pre> julia> happy(8)
Line 3,420:
31</pre>
A recursive version:
<
function ishappy(x, mem = [])
Line 3,431:
happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-1]]
</syntaxhighlight>
{{Out}}
<pre>julia> show(happy(8))
Line 3,439:
Faster with use of cache
{{trans|C}}
<
buf = zeros(Int,CACHE)
buf[1] = 1
Line 3,468:
end
return i-1
end</
=={{header|K}}==
<
hpy 1+!100
Line 3,477:
8#hpy 1+!100
1 7 10 13 19 23 28 31</
Another implementation which is easy to follow is given below:
<syntaxhighlight lang="k">
/ happynum.k
Line 3,490:
hnum: {[x]; h::();i:1;while[(#h)<x; :[(isHappy i); h::(h,i)]; i+:1]; `0: ,"List of ", ($x), " Happy Numbers"; h}
</syntaxhighlight>
The output of a session with this implementation is given below:
Line 3,505:
=={{header|Kotlin}}==
{{trans|C#}}
<
fun isHappy(n: Int): Boolean {
Line 3,534:
}
println("First 8 happy numbers : " + happyNums.joinToString(", "))
}</
{{out}}
Line 3,542:
=={{header|Lasso}}==
<
define isHappy(n::integer) => {
Line 3,556:
where isHappy(#x)
take 8
select #x</
Output:
<
=={{header|Liberty BASIC}}==
<
n = 0
DO
Line 3,588:
sqrInts$ = sqrInts$ + Str$(sqrInts) + ":"
HappyN = HappyN(sqrInts, sqrInts$)
END FUNCTION</
Output:-
<pre>1 1
Line 3,602:
=={{header|Locomotive Basic}}==
<
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</
[[File:Happy Numbers, Locomotive BASIC.png]]
Line 3,623:
=={{header|Logo}}==
<
output (apply "sum (map [[d] d*d] ` :number))
end
Line 3,646:
print n_happy 8
bye</
Output:
Line 3,654:
{{works with|lci 0.10.3}}
<
Happy Numbers Rosetta Code task in LOLCODE
Requires 1.3 for BUKKIT availability
Line 3,736:
OIC
IM OUTTA YR LOOP
KTHXBYE</
Output:<pre>1
Line 3,748:
=={{header|Lua}}==
<
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</
Output:
<pre>1
Line 3,779:
<syntaxhighlight lang="m2000 interpreter">
Function FactoryHappy {
sumOfSquares= lambda (n) ->{
Line 3,812:
PrintHappy=factoryHappy()
Call PrintHappy()
</syntaxhighlight>
{{out}}
<pre>
Line 3,826:
=={{header|MAD}}==
<
BOOLEAN CYCLE
DIMENSION CYCLE(200)
Line 3,854:
END OF PROGRAM
</syntaxhighlight>
{{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.)
<
local s := 0;
local m := n;
Line 3,876:
end do;
s
end proc:</
(Note that the unevaluation quotes on the third argument to irem are essential here, as that argument must be a name and, if m were passed without quotes, it would evaluate to a number.)
For example,
<syntaxhighlight lang="maple">
> SumSqDigits( 1234567890987654321 );
570
</syntaxhighlight>
We can check this by computing it another way (more directly).
<syntaxhighlight lang="maple">
> n := 1234567890987654321:
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
570
</syntaxhighlight>
The most straight-forward way to check whether a number is happy or sad seems also to be the fastest (that I could think of).
<
if n = 1 then
true
Line 3,903:
evalb( s = 1 )
end if
end proc:</
We can use this to determine the number of happy (H) and sad (S) numbers up to one million as follows.
<syntaxhighlight lang="maple">
> H, S := selectremove( Happy?, [seq]( 1 .. N ) ):
> nops( H ), nops( S );
143071, 856929
</syntaxhighlight>
Finally, to solve the stated problem, here is a completely straight-forward routine to locate the first N happy numbers, returning them in a set.
<
local count := 0;
local T := table();
Line 3,921:
end do;
{seq}( T[ i ], i = 1 .. count )
end proc:</
With input equal to 8, we get
<syntaxhighlight lang="maple">
> FindHappiness( 8 );
{1, 7, 10, 13, 19, 23, 28, 31}
</syntaxhighlight>
For completeness, here is an implementation of the cycle detection algorithm for recognizing happy numbers. It is much slower, however.
<
local a, b;
a, b := n, SumSqDigits( n );
Line 3,936:
end do;
evalb( a = 1 )
end proc:</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Custom function HappyQ:
<
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1</
Examples for a specific number:
<
HappyQ[137]</
gives back:
<syntaxhighlight lang="mathematica">True
False</
Example finding the first 8:
<
n = 1;
i = 0;
Line 3,961:
]
]
happynumbers</
gives back:
<
=={{header|MATLAB}}==
Recursive version:
<
nHappy = 0;
k = 1;
Line 3,988:
hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]);
end
end</
{{out}}
<pre>1 7 10 13 19 23 28 31 </pre>
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
fn isHappyNumber n =
(
Line 4,020:
)
</syntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
1
7
Line 4,031:
28
31
</syntaxhighlight>
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 4,073:
:- func sqr(int) = int.
sqr(X) = X * X.</
{{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.
<
while true
if x == 89 then return false
Line 4,098:
i = i + 1
end while
print "First 8 happy numbers: " + found</
{{out}}
<pre>First 8 happy numbers: [1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 4,104:
=={{header|ML}}==
==={{header|mLite}}===
<
A happy number is defined by the following process. Starting with any positive integer, replace the number
by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will
Line 4,139:
foreach (fn n = (print n; print " is "; println ` happy n)) ` iota 10;
</syntaxhighlight>
Output:
<pre>1 is happy
Line 4,153:
=={{header|Modula-2}}==
<
FROM InOut IMPORT WriteCard, WriteLn;
Line 4,196:
INC(num);
END;
END HappyNumbers.</
{{out}}
<pre> 1
Line 4,208:
=={{header|MUMPS}}==
<
;Determines if a number N is a happy number
;Note that the returned strings do not have a leading digit unless it is a happy number
Line 4,231:
FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1
KILL I
QUIT</
Output:<pre>
USER>D HAPPY^ROSETTA(8)
Line 4,253:
=={{header|NetRexx}}==
{{trans|REXX}}
<
limit = arg[0] /*get argument for LIMIT. */
say limit
Line 4,280:
q=sum /*now, lets try the Q sum. */
end
end</
;Output
<pre>
Line 4,398:
=={{header|Nim}}==
{{trans|Python}}
<
proc happy(n: int): bool =
Line 4,417:
for x in 0..31:
if happy(x):
echo x</
Output:
<pre>1
Line 4,429:
=={{header|Objeck}}==
<
use Structure;
Line 4,475:
}
}
}</
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]].
<
let step =
Line 4,505:
List.iter print_endline (
List.rev_map string_of_num (first 8)) ;;</
Output:
<pre>$ ocaml nums.cma happy_numbers.ml
Line 4,519:
=={{header|Oforth}}==
<
| cycle |
ListBuffer new ->cycle
Line 4,534:
ListBuffer new ->numbers
1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup numbers add ] 1+ ]
numbers println ;</
Output:
Line 4,543:
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
count = 0
say "First 8 happy numbers are:"
Line 4,572:
number = next
end
</syntaxhighlight>
<pre>
First 8 happy numbers are:
Line 4,586:
=={{header|Oz}}==
<
import
System
Line 4,629:
in
{System.show {List.take HappyNumbers 8}}
end</
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.
<
isHappy(n)={
if(n<262,
Line 4,645:
)
};
select(isHappy, vector(31,i,i))</
Output:
<pre>%1 = [1, 7, 10, 13, 19, 23, 28, 31]</pre>
=={{header|Pascal}}==
<
uses
Line 4,710:
end;
writeln;
end.</
Output:
<pre>:> ./HappyNumbers
Line 4,721:
Extended to 10e18
Tested with Free Pascal 3.0.4
<
{$IFDEF FPC}
{$MODE DELPHI}
Line 4,970:
writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0));
end.
</syntaxhighlight>
;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.
<
sub ishappy {
Line 5,033:
my $n = 0;
print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n";</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,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}}
<
sub is_happy {
my ($n) = @_;
Line 5,051:
my $n;
is_happy( ++$n ) and print "$n " or redo for 1..8;</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Line 5,057:
=={{header|Phix}}==
Copy of [[Happy_numbers#Euphoria|Euphoria]] tweaked to give a one-line output
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">is_happy</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">seen</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 5,084:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--</
{{out}}
<pre>
Line 5,092:
=={{header|PHP}}==
{{trans|D}}
<
while (1) {
$total = 0;
Line 5,115:
}
$i++;
}</
<pre>1 7 10 13 19 23 28 31 </pre>
=={{header|Picat}}==
<
println(happy_len(8)).
Line 5,143:
end,
N := N + 1
end.</
{{out}}
Line 5,149:
=={{header|PicoLisp}}==
<
(let Seen NIL
(loop
Line 5,161:
(do 8
(until (happy? (inc 'H)))
(printsp H) ) )</
Output:
<pre>1 7 10 13 19 23 28 31</pre>
=={{header|PILOT}}==
<
:n=0
:i=0
Line 5,202:
:x=y
J (x):*digit
E :</
{{out}}
<pre>1
Line 5,214:
=={{header|PL/I}}==
<
declare (i, j, n, m, nh initial (0) ) fixed binary (31);
Line 5,238:
end;
end test;
</syntaxhighlight>
OUTPUT:
<pre>
Line 5,252:
=={{header|PL/M}}==
<
/* FIND SUM OF SQUARE OF DIGITS OF NUMBER */
Line 5,322:
CALL BDOS(0,0);
EOF</
{{out}}
<pre>1
Line 5,334:
=={{header|Potion}}==
<
isHappy = (n) :
Line 5,353:
if (isHappy(i)): firstEight append(i).
.
firstEight string print</
=={{header|PowerShell}}==
<
$a=@()
for($i=2;$a.count -lt $n;$i++) {
Line 5,375:
}
$a -join ','
}</
Output :
<
7,10,13,19,23,28,31,32</
=={{header|Prolog}}==
{{Works with|SWI-Prolog}}
<
% creation of the list
length(L, Nb),
Line 5,428:
square(N, SN) :-
SN is N * N.</
Output :
<
L = [1,7,10,13,19,23,28,31].</
=={{header|PureBasic}}==
<
#MaxTests=100
#True = 1: #False = 0
Line 5,467:
Until i>#MaxTests
ProcedureReturn #False
EndProcedure</
Sample output:
<pre>#1 1
Line 5,480:
=={{header|Python}}==
===Procedural===
<
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]</
===Composition of pure functions===
Drawing 8 terms from a non finite stream, rather than assuming prior knowledge of the finite sample size required:
<
from itertools import islice
Line 5,573:
if __name__ == '__main__':
main()</
{{Out}}
<pre>[1, 7, 10, 13, 19, 23, 28, 31]</pre>
Line 5,579:
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">
[ 0 swap
[ 10 /mod 2 **
Line 5,601:
drop nip ] is happies ( n --> [ )
8 happies echo</
{{Out}}
Line 5,608:
=={{header|R}}==
<
{
stopifnot(is.numeric(n) && length(n)==1)
Line 5,636:
}
happy
}</
Example usage
<syntaxhighlight lang
[1] FALSE
attr(,"cycle")
[1] 4 16 37 58 89 145 42 20
<
which(apply(rbind(1:50), 2, is.happy))</
1 7 10 13 19 23 28 31 32 44 49
<
happies <- c()
i <- 1L
Line 5,653:
i <- i + 1L
}
happies</
1 7 10 13 19 23 28 31
=={{header|Racket}}==
<
(define (sum-of-squared-digits number (result 0))
(if (zero? number)
Line 5,678:
x))
(display (take (get-happys 100) 8)) ;displays (1 7 10 13 19 23 28 31)</
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-13}}
<syntaxhighlight lang="raku"
loop {
state %seen;
Line 5,692:
}
say join ' ', grep(&happy, 1 .. *)[^8];</
{{out}}
<pre>1 7 10 13 19 23 28 31</pre>
Here's another approach that uses a different set of tricks including lazy lists, gather/take, repeat-until, and the cross metaoperator X.
<syntaxhighlight lang="raku"
my %stopper = 1 => 1;
my $n = $number;
Line 5,705:
}
say ~@happy[^8];</
Output is the same as above.
Here is a version using a subset and an anonymous recursion (we cheat a little bit by using the knowledge that 7 is the second happy number):
<syntaxhighlight lang="raku"
$n == 1 ?? True !!
$n < 7 ?? False !!
Line 5,715:
}
say (grep Happy, 1 .. *)[^8];</
Again, output is the same as above. It is not clear whether this version returns in finite time for any integer, though.
Line 5,721:
=={{header|Relation}}==
<syntaxhighlight lang="relation">
function happy(x)
set y = x
Line 5,753:
set i = i + 1
end while
</syntaxhighlight>
<pre>
Line 5,768:
=={{header|REXX}}==
===unoptimized===
<
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. */</
{{out|output|text= when using the input of: <tt> 8 </tt>}}
<pre>
Line 5,804:
<br><br>This REXX version also accepts a ''range'' of happy numbers to be shown, that is,
<br>it can show the 2000<sup>th</sup> through the 2032<sup>nd</sup> (inclusive) happy numbers (as shown below).
<
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. */</
{{out|output|text= when using the input of: <tt> 2000 2032 </tt>}}
<pre>
Line 5,870:
===optimized, horizontal list===
This REXX version is identical to the optimized version, but displays the numbers in a horizontal list.
<
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. */</
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).
Line 5,957:
=={{header|Ring}}==
<
found = 0
Line 5,981:
End
Return True
</syntaxhighlight>
{{out}}
<pre>
Line 5,997:
{{works with|Ruby|2.1}}
<
@seen_numbers = Set.new
Line 6,015:
false # Return false
end
end</
Helper method to produce output:
<
happy_numbers = []
Line 6,029:
end
print_happy</
{{out}}
<
===Alternative version===
<
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</
{{out}}
Line 6,081:
===Simpler Alternative===
{{trans|Python}}
<
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) }</
{{out}}
<pre>
Line 6,120:
=={{header|Run BASIC}}==
<
if happy(i) = 1 then
cnt = cnt + 1
Line 6,138:
num = happy
wend
end function</
<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)
<
fn sumsqd(mut n: i32) -> i32 {
Line 6,186:
println!("{:?}", happy)
}</
{{out}}
<pre>
Line 6,193:
=={{header|Salmon}}==
<
outer:
iterate(x; [1...+oo])
Line 6,221:
now := new;
};
};</
This Salmon program produces the following output:
<pre>1 is happy.
Line 6,233:
=={{header|Scala}}==
<
| new Iterator[Int] {
| val seen = scala.collection.mutable.Set[Int]()
Line 6,257:
28
31
</syntaxhighlight>
=={{header|Scheme}}==
<
(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))))</
The output is:
<pre>happy numbers: 1 7 10 13 19 23 28 31</pre>
Line 6,288:
=={{header|Seed7}}==
<
const type: cacheType is hash [integer] boolean;
Line 6,329:
end if;
end for;
end func;</
Output:
Line 6,347:
=={{header|SequenceL}}==
<
import <Utilities/Conversion.sl>;
Line 6,373:
true when n = 1
else
isHappyHelper(newN, cache ++ [n]);</
{{out}}
Line 6,382:
=={{header|SETL}}==
<
s := [n];
while n > 1 loop
Line 6,391:
end while;
return true;
end proc;</
<
n := 1;
until #happy = 8 loop
Line 6,399:
end loop;
print(happy);</
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
Alternative version:
<
Output:
<pre>[1 7 10 13 19 23 28 31]</pre>
=={{header|Sidef}}==
<
static seen = Hash()
Line 6,418:
}
say happy.first(8)</
{{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.
<
|cache negativeCache|
HappyNumber class >> new [ |me|
Line 6,491:
]
]
].</
<
happy := HappyNumber new.
Line 6,498:
(happy isHappy: i)
ifTrue: [ i displayNl ]
].</
Output:
1
Line 6,511:
an alternative version is:
{{works with|Smalltalk/X}}
<
next :=
Line 6,535:
try := try + 1
].
happyNumbers printCR</
Output:
OrderedCollection(1 7 10 13 19 23 28 31)
=={{header|Swift}}==
<
var cycle = [Int]()
Line 6,564:
}
count++
}</
{{out}}
<pre>
Line 6,578:
=={{header|Tcl}}==
using code from [[Sum of squares#Tcl]]
<
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]"</
<pre>the first 8 happy numbers are: {1 7 10 13 19 23 28 31}</pre>
=={{header|TUSCRIPT}}==
<
SECTION check
IF (n!=1) THEN
Line 6,632:
DO check
ENDLOOP
ENDLOOP</
Output:
<pre>
Line 6,646:
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">
' ************************
' MAIN
Line 6,709:
' END SUBS & FUNCTIONS
' ************************
</syntaxhighlight>
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
<
function sum_of_square_digits
{
Line 6,752:
}
first_n_happy 8</
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.
<
#import nat
Line 6,775:
#cast %nL
main = (first happy) 8</
output:
<pre><1,7,10,13,19,23,28,31></pre>
Line 6,781:
=={{header|Vala}}==
{{libheader|Gee}}
<
/* function to sum the square of the digits */
Line 6,826:
stdout.printf("%d ", num);
stdout.printf("\n");
} // end main</
The output is:
<pre>
Line 6,834:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 6,864:
Is_Happy_Number = True
End Function
</syntaxhighlight>
{{Out}}
<pre>Is Happy : 1
Line 6,876:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
count = 0
firsteigth=""
Line 6,907:
Loop
End Function
</syntaxhighlight>
{{Out}}
Line 6,914:
=={{header|Visual Basic .NET}}==
This version uses Linq to carry out the calculations.
<
Sub Main()
Dim n As Integer = 1
Line 6,942:
Return True
End Function
End Module</
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.
<
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</
{{out}}
<pre>---Happy Numbers---
Line 7,009:
=={{header|Vlang}}==
{{trans|go}}
<
mut m := map[int]bool{}
mut n := h
Line 7,034:
}
println('')
}</
{{out}}
<pre>
Line 7,042:
=={{header|Wren}}==
{{trans|Go}}
<
var m = {}
while (n > 1) {
Line 7,067:
n = n + 1
}
System.print()</
{{out}}
Line 7,081:
numbers.
<
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
]</
Output:
Line 7,140:
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = std.io.getStdOut().outStream();
Line 7,177:
return s;
}
</syntaxhighlight>
{{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}}
<
foreach N in ([1..]){
n:=N; while(1){
Line 7,193:
}
}
}</
<
h.walk(8).println();</
{{out}}
<pre>L(1,7,10,13,19,23,28,31)</pre>
Get the one million-th happy number. Nobody would call this quick.
<
{{out}}<pre>7105849</pre>
=={{header|ZX Spectrum Basic}}==
{{trans|Run_BASIC}}
<
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</
|