Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Happy_numbers
note: Arithmetic operations

View file

@ -0,0 +1,21 @@
From Wikipedia, the free encyclopedia:
:: A [[wp:Happy number|happy number]] is defined by the following process:
:: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   '''1'''   (where it will stay),   or it loops endlessly in a cycle which does not include   '''1'''.  
<br>
:: Those numbers for which this process end in &nbsp; '''1''' &nbsp; are &nbsp; &nbsp; &nbsp; ''happy'' &nbsp; numbers, &nbsp;
:: while &nbsp; those numbers &nbsp; that &nbsp; do &nbsp; <u>not</u> &nbsp; end in &nbsp; '''1''' &nbsp; are &nbsp; ''unhappy'' &nbsp; numbers.
;Task:
Find and print the first &nbsp; '''8''' &nbsp; happy numbers.
Display an example of your output here on this page.
;See also:
* &nbsp; The OEIS entry: &nbsp; [[oeis:A007770|The &nbsp; &nbsp; happy numbers: &nbsp; A007770]]
* &nbsp; The OEIS entry: &nbsp; [[oeis:A031177|The unhappy numbers; &nbsp; A031177]]
<br><br>

View file

@ -0,0 +1,10 @@
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
print((0.<500).filter(x -> happy(x))[0.<8])

View file

@ -0,0 +1,77 @@
flags: equ 2 ; 256-byte page in which to keep track of cycles
puts: equ 9 ; CP/M print string
bdos: equ 5 ; CP/M entry point
org 100h
lxi d,0108h ; D=current number to test, E=amount of numbers
;;; Is D happy?
number: mvi a,1 ; We haven't seen any numbers yet, set flags to 1
lxi h,256*flags
init: mov m,a
inr l
jnz init
mov a,d ; Get digits
step: call digits
mov l,a ; L = D1 * D1
mov h,a
xra a
sqr1: add h
dcr l
jnz sqr1
mov l,a
mov h,b ; L += D10 * D10
xra a
sqr10: add h
dcr b
jnz sqr10
add l
mov l,a
mov h,c ; L += D100 * D100
xra a
sqr100: add h
dcr c
jnz sqr100
add l
mov l,a
mvi h,flags ; Look up corresponding flag
dcr m ; Will give 0 the first time and not-0 afterwards
mov a,l ; If we haven't seen the number before, another step
jz step
dcr l ; If we _had_ seen it, then is it 1?
jz happy ; If so, it is happy
next: inr d ; Afterwards, try next number
jmp number
happy: mov a,d ; D is happy - get its digits (for output)
lxi h,string+3
call digits ; Write digits into string for output
call sdgt ; Ones digit,
mov a,b ; Tens digit,
call sdgt
mov a,c ; Hundreds digit
call sdgt
push d ; Keep counters on stack
mvi c,puts ; Print string using CP/M call
xchg
call bdos
pop d ; Restore counters
dcr e ; One fewer happy number left
jnz next ; If we need more, do the next one
ret
;;; Store A as ASCII digit in [HL] and go to previous digit
sdgt: adi '0'
dcx h
mov m,a
ret
;;; Get digits of 8-bit number in A.
;;; Input: A = number
;;; Output: C=100s digit, B=10s digit, A=1s digit
digits: lxi b,-1 ; Set B and C to -1 (correct for extra loop cycle)
d100: inr c ; Calculate hundreds digit
sui 100 ; By trial subtraction of 100
jnc d100 ; Until underflow occurs
adi 100 ; Loop runs one cycle too many, so add 100 back
d10: inr b ; Calculate 10s digit in the same way
sui 10
jnc d10
adi 10
ret ; 1s digit is left in A afterwards
string: db '000',13,10,'$'

View file

@ -0,0 +1,29 @@
: until! "not while!" eval i;
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? ' sumsqd cycle 1 = ;
: .happy \ n --
1 repeat
dup happy? if dup . space swap 1- swap then 1+
over 0 > while!
2drop cr ;
;with
;with

View file

@ -0,0 +1,25 @@
(include-book "arithmetic-3/top" :dir :system)
(defun sum-of-digit-squares (n)
(if (zp n)
0
(+ (expt (mod n 10) 2)
(sum-of-digit-squares (floor n 10)))))
(defun is-happy-r (n seen)
(let ((next (sum-of-digit-squares n)))
(cond ((= next 1) t)
((member next seen) nil)
(t (is-happy-r next (cons next seen))))))
(defun is-happy (n)
(is-happy-r n nil))
(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)))))
(defun first-happy-nums (n)
(first-happy-nums-r n 1))

View file

@ -0,0 +1,25 @@
INT base10 = 10, num happy = 8;
PROC next = (INT in n)INT: (
INT n := in n;
INT out := 0;
WHILE n NE 0 DO
out +:= ( n MOD base10 ) ** 2;
n := n OVER base10
OD;
out
);
PROC is happy = (INT in n)BOOL: (
INT n := in n;
FOR i WHILE n NE 1 AND n NE 4 DO n := next(n) OD;
n=1
);
INT count := 0;
FOR i WHILE count NE num happy DO
IF is happy(i) THEN
count +:= 1;
print((i, new line))
FI
OD

View file

@ -0,0 +1,38 @@
begin
integer function mod(a,b);
integer a,b;
mod := a-(a/b)*b;
integer function sumdgtsq(n);
integer n;
sumdgtsq :=
if n = 0 then 0
else mod(n,10)*mod(n,10) + sumdgtsq(n/10);
integer function happy(n);
integer n;
begin
integer i;
integer array seen[0:200];
for i := 0 step 1 until 200 do seen[i] := 0;
while seen[n] = 0 do
begin
seen[n] := 1;
n := sumdgtsq(n);
end;
happy := if n = 1 then 1 else 0;
end;
integer i, n;
i := n := 0;
while n < 8 do
begin
if happy(i) = 1 then
begin
write(i);
n := n + 1;
end;
i := i + 1;
end;
end

View file

@ -0,0 +1,36 @@
begin % find some happy numbers: numbers whose digit-square sums become 1 %
% when repeatedly applied %
% returns true if n is happy, false otherwise %
logical procedure isHappy ( integer value n ) ;
begin
% in base ten, numbers either reach 1 or loop around a sequence %
% containing 4 (see the Wikipedia article) %
integer v, dSum, d;
v := abs n;
if v > 1 then begin
while begin
dSum := 0;
while v not = 0 do begin
d := v rem 10;
v := v div 10;
dSum := dSum + ( d * d )
end while_v_ne_0 ;
v := dSum;
v not = 1 and v not = 4
end do begin end
end if_v_ne_0 ;
v = 1
end isHappy ;
begin % find the first 8 happy numbers %
integer n, hCount;
hCount := 0;
n := 1;
while hCount < 8 do begin
if isHappy( n ) then begin
writeon( i_w := 1, s_w := 0, " ", n );
hCount := hCount + 1
end if_isHappy__n ;
n := n + 1
end while_hCount_lt_10
end
end.

View file

@ -0,0 +1,20 @@
HappyNumbers arg;⎕IO;∆roof;∆first;bin;iroof
[1] ⍝0: Happy number
[2] ⍝1: http://rosettacode.org/wiki/Happy_numbers
[3] ⎕IO1 ⍝ Index origin
[4] ∆roof ∆first2arg,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¨∆firstbin/iroof ⍝ Show ∆first numbers, but not 0

View file

@ -0,0 +1,14 @@
HappyNumbers{ ⍝ return the first ⍵ Happy Numbers
⍝ initial list
=+/: ⍝ 1's mark happy numbers
sq× ⍝ square function (times selfie)
isHappy{ ⍝ is ⍵ a happy number?
⍝ previous sums
=1:1 ⍝ if we get to 1, it's happy
n+/sq¨ ⍝ sum of the square of the digits
n:0 ⍝ if we hit this sum before, it's not happy
(,n) n} ⍝ recurse until it's happy or not
(,isHappy 1+) ⍝ recurse until we have ⍵ happy numbers
}
HappyNumbers 8
1 7 10 13 19 23 28 31

View file

@ -0,0 +1,41 @@
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
}
}
}

View file

@ -0,0 +1,28 @@
BEGIN {
for (i = 1; i < 50; ++i){
if (isHappy(i)) {
print i;
}
}
exit
}
function isHappy(n, seen) {
delete seen;
while (1) {
n = sumSqrDig(n)
if (seen[n]) {
return n == 1
}
seen[n] = 1
}
}
function sumSqrDig(n, d, tot) {
while (n) {
d = n % 10
tot += d * d
n = int(n/10)
}
return tot
}

View file

@ -0,0 +1,51 @@
BYTE FUNC SumOfSquares(BYTE x)
BYTE sum,d
sum=0
WHILE x#0
DO
d=x MOD 10
d==*d
sum==+d
x==/10
OD
RETURN (sum)
BYTE FUNC Contains(BYTE ARRAY a BYTE count,x)
BYTE i
FOR i=0 TO count-1
DO
IF a(i)=x THEN RETURN (1) FI
OD
RETURN (0)
BYTE FUNC IsHappyNumber(BYTE x)
BYTE ARRAY cache(100)
BYTE count
count=0
WHILE x#1
DO
cache(count)=x
count==+1
x=SumOfSquares(x)
IF Contains(cache,count,x) THEN
RETURN (0)
FI
OD
RETURN (1)
PROC Main()
BYTE x,count
x=1 count=0
WHILE count<8
DO
IF IsHappyNumber(x) THEN
count==+1
PrintF("%I: %I%E",count,x)
FI
x==+1
OD
RETURN

View file

@ -0,0 +1,42 @@
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();

View file

@ -0,0 +1,41 @@
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Ordered_Sets;
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;

View file

@ -0,0 +1,32 @@
on run
set howManyHappyNumbers to 8
set happyNumberList to {}
set globalCounter to 1
repeat howManyHappyNumbers times
repeat while not isHappy(globalCounter)
set globalCounter to globalCounter + 1
end repeat
set end of happyNumberList to globalCounter
set globalCounter to globalCounter + 1
end repeat
log happyNumberList
end run
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

View file

@ -0,0 +1,127 @@
---------------------- HAPPY NUMBERS -----------------------
-- isHappy :: Int -> Bool
on isHappy(n)
-- endsInOne :: [Int] -> Int -> Bool
script endsInOne
-- sumOfSquaredDigits :: Int -> Int
script sumOfSquaredDigits
-- digitSquared :: Int -> Int -> Int
script digitSquared
on |λ|(a, x)
(a + (x as integer) ^ 2) as integer
end |λ|
end script
on |λ|(n)
foldl(digitSquared, 0, splitOn("", n as string))
end |λ|
end script
-- [Int] -> Int -> Bool
on |λ|(s, n)
if n = 1 then
true
else
if s contains n then
false
else
|λ|(s & n, |λ|(n) of sumOfSquaredDigits)
end if
end if
end |λ|
end script
endsInOne's |λ|({}, n)
end isHappy
--------------------------- TEST ---------------------------
on run
-- seriesLength :: {n:Int, xs:[Int]} -> Bool
script seriesLength
property target : 8
on |λ|(rec)
length of xs of rec = target of seriesLength
end |λ|
end script
-- succTest :: {n:Int, xs:[Int]} -> {n:Int, xs:[Int]}
script succTest
on |λ|(rec)
tell rec to set {xs, n} to {its xs, its n}
script testResult
on |λ|(x)
if isHappy(x) then
xs & x
else
xs
end if
end |λ|
end script
{n:n + 1, xs:testResult's |λ|(n)}
end |λ|
end script
xs of |until|(seriesLength, succTest, {n:1, xs:{}})
--> {1, 7, 10, 13, 19, 23, 28, 31}
end run
-------------------- GENERIC FUNCTIONS ---------------------
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
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
-- splitOn :: String -> String -> [String]
on splitOn(pat, src)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, pat}
set xs to text items of src
set my text item delimiters to dlm
return xs
end splitOn
-- until :: (a -> Bool) -> (a -> a) -> a -> a
on |until|(p, f, x)
set mp to mReturn(p)
set v to x
tell mReturn(f)
repeat until mp's |λ|(v)
set v to |λ|(v)
end repeat
end tell
return v
end |until|

View file

@ -0,0 +1 @@
{1, 7, 10, 13, 19, 23, 28, 31}

View file

@ -0,0 +1,7 @@
0 C = 8: DIM S(16):B = 10: PRINT "THE FIRST "C" HAPPY NUMBERS": FOR R = C TO 0 STEP 0:N = H: GOSUB 1: PRINT MID$ (" " + STR$ (H),1 + (R = C),255 * I);:R = R - I:H = H + 1: NEXT R: END
1 S = 0: GOSUB 3:I = N = 1: IF NOT Q THEN RETURN
2 FOR Q = 1 TO 0 STEP 0:S(S) = N:S = S + 1: GOSUB 6:N = T: GOSUB 3: NEXT Q:I = N = 1: RETURN
3 Q = N > 1: IF NOT Q OR NOT S THEN RETURN
4 Q = 0: FOR I = 0 TO S - 1: IF N = S(I) THEN RETURN
5 NEXT I:Q = 1: RETURN
6 T = 0: FOR I = N TO 0 STEP 0:M = INT (I / B):T = INT (T + (I - M * B) ^ 2):I = M: NEXT I: RETURN

View file

@ -0,0 +1,21 @@
ord0: to :integer `0`
happy?: function [x][
n: x
past: new []
while [n <> 1][
s: to :string n
n: 0
loop s 'c [
i: (to :integer c) - ord0
n: n + i * i
]
if contains? past n -> return false
'past ++ n
]
return true
]
loop 0..31 'x [
if happy? x -> print x
]

View file

@ -0,0 +1,21 @@
Loop {
If isHappy(A_Index) {
out .= (out="" ? "" : ",") . A_Index
i ++
If (i = 8) {
MsgBox, The first 8 happy numbers are: %out%
ExitApp
}
}
}
isHappy(num, list="") {
list .= (list="" ? "" : ",") . num
Loop, Parse, num
sum += A_LoopField ** 2
If (sum = 1)
Return true
Else If sum in %list%
Return false
Else Return isHappy(sum, list)
}

View file

@ -0,0 +1,18 @@
while h < 8
if (Happy(A_Index)) {
Out .= A_Index A_Space
h++
}
MsgBox, % Out
Happy(n) {
Loop, {
Loop, Parse, n
t += A_LoopField ** 2
if (t = 89)
return, 0
if (t = 1)
return, 1
n := t, t := 0
}
}

View file

@ -0,0 +1,22 @@
$c = 0
$k = 0
While $c < 8
$k += 1
$n = $k
While $n <> 1
$s = StringSplit($n, "")
$t = 0
For $i = 1 To $s[0]
$t += $s[$i] ^ 2
Next
$n = $t
Switch $n
Case 4,16,37,58,89,145,42,20
ExitLoop
EndSwitch
WEnd
If $n = 1 Then
ConsoleWrite($k & " is Happy" & @CRLF)
$c += 1
EndIf
WEnd

View file

@ -0,0 +1,24 @@
$c = 0
$k = 0
While $c < 8
$a = ObjCreate("System.Collections.ArrayList")
$k += 1
$n = $k
While $n <> 1
If $a.Contains($n) Then
ExitLoop
EndIf
$a.add($n)
$s = StringSplit($n, "")
$t = 0
For $i = 1 To $s[0]
$t += $s[$i] ^ 2
Next
$n = $t
WEnd
If $n = 1 Then
ConsoleWrite($k & " is Happy" & @CRLF)
$c += 1
EndIf
$a.Clear
WEnd

View file

@ -0,0 +1,25 @@
n = 1 : cnt = 0
print "The first 8 isHappy numbers are:"
print
while cnt < 8
if isHappy(n) = 1 then
cnt += 1
print cnt; " => "; n
end if
n += 1
end while
function isHappy(num)
isHappy = 0
cont = 0
while cont < 50 and isHappy <> 1
num$ = string(num)
cont += 1
isHappy = 0
for i = 1 to length(num$)
isHappy += int(mid(num$,i,1)) ^ 2
next i
num = isHappy
end while
end function

View file

@ -0,0 +1,21 @@
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)

View file

@ -0,0 +1,25 @@
get "libhdr"
let sumdigitsq(n) =
n=0 -> 0, (n rem 10)*(n rem 10)+sumdigitsq(n/10)
let happy(n) = valof
$( let seen = vec 255
for i = 0 to 255 do i!seen := false
$( n!seen := true
n := sumdigitsq(n)
$) repeatuntil n!seen
resultis 1!seen
$)
let start() be
$( let n, i = 0, 0
while n < 8 do
$( if happy(i) do
$( n := n + 1
writef("%N ",i)
$)
i := i + 1
$)
wrch('*N')
$)

View file

@ -0,0 +1,3 @@
SumSqDgt +´2˜ •Fmt-'0'˙
Happy {𝕨((˜ )𝕊(SumSqDgt),1=)𝕩}
8Happy¨/50

View file

@ -0,0 +1,81 @@
@echo off
setlocal enableDelayedExpansion
::Define a list with 10 terms as a convenience for defining a loop
set "L10=0 1 2 3 4 5 6 7 8 9"
shift /1 & goto %1
exit /b
:list min count
:: This routine prints all happy numbers > min (arg1)
:: until it finds count (arg2) happy numbers.
set /a "n=%~1, cnt=%~2"
call :listInternal
exit /b
:test min [max]
:: This routine sequentially tests numbers between min (arg1) and max (arg2)
:: to see if they are happy. If max is not specified then it defaults to min.
set /a "min=%~1"
if "%~2" neq "" (set /a "max=%~2") else set max=%min%
::The FOR /L loop does not detect integer overflow, so must protect against
::an infinite loop when max=0x7FFFFFFFF
set end=%max%
if %end% equ 2147483647 set /a end-=1
for /l %%N in (%min% 1 %end%) do (
call :testInternal %%N && (echo %%N is happy :^)) || echo %%N is sad :(
)
if %end% neq %max% call :testInternal %max% && (echo %max% is happy :^)) || echo %max% is sad :(
exit /b
: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 %%. in (
%L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10% %L10%
) do (
call :testInternal !n! && (
echo !n!
set /a cnt-=1
if !cnt! leq 0 exit /b 0
)
if !n! equ 2147483647 (
>&2 echo ERROR: Maximum integer value reached
exit /b 1
)
set /a n+=1
)
goto :listInternal
: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
set n=%1
for %%. in (%L10% %L10% %L10%) do (
if !n!==1 exit /b 0
%= Only numbers < 1000 can cycle =%
if !n! lss 1000 (
if defined t.!n! exit /b 1
set t.!n!=1
)
%= Sum the squared digits =%
%= Batch can't handle numbers greater than 10 digits so we can use =%
%= a constrained FOR loop and avoid a slow goto =%
set sum=0
for /l %%N in (1 1 10) do (
if !n! gtr 0 set /a "sum+=(n%%10)*(n%%10), n/=10"
)
set /a n=sum
)

View file

@ -0,0 +1,36 @@
bool isHappy (int n)
{
ints cache;
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;
while (happynums.count() < 8)
{
if (isHappy(num))
happynums.add(num);
num++;
}
puts("First 8 happy numbers : " + str.newline + happynums);
}

View file

@ -0,0 +1,29 @@
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 }
}
happy? = { n, seen = set.new |
when {true? happiness.include? n } { happiness.merge seen << n; true }
{ true? sadness.include? n } { sadness.merge seen; false }
{ true? seen.include? n } { sadness.merge seen; false }
{ true } { seen << n; happy? sum_of_squares_of_digits(n), seen }
}
num = 1
happies = []
while { happies.length < 8 } {
true? happy?(num)
{ happies << num }
num = num + 1
}
p "First eight happy numbers: #{happies}"
p "Happy numbers found: #{happiness.to_array.sort}"
p "Sad numbers found: #{sadness.to_array.sort}"

View file

@ -0,0 +1,36 @@
#include <map>
#include <set>
bool happy(int number) {
static std::map<int, bool> cache;
std::set<int> cycle;
while (number != 1 && !cycle.count(number)) {
if (cache.count(number)) {
number = cache[number] ? 1 : 0;
break;
}
cycle.insert(number);
int newnumber = 0;
while (number > 0) {
int digit = number % 10;
newnumber += digit * digit;
number /= 10;
}
number = newnumber;
}
bool happiness = number == 1;
for (std::set<int>::const_iterator it = cycle.begin();
it != cycle.end(); it++)
cache[*it] = happiness;
return happiness;
}
#include <iostream>
int main() {
for (int i = 1; i < 50; i++)
if (happy(i))
std::cout << i << std::endl;
return 0;
}

View file

@ -0,0 +1,41 @@
unsigned int happy_iteration(unsigned int n)
{
unsigned int result = 0;
while (n > 0)
{
unsigned int lastdig = n % 10;
result += lastdig*lastdig;
n /= 10;
}
return result;
}
bool is_happy(unsigned int n)
{
unsigned int n2 = happy_iteration(n);
while (n != n2)
{
n = happy_iteration(n);
n2 = happy_iteration(happy_iteration(n2));
}
return n == 1;
}
#include <iostream>
int main()
{
unsigned int current_number = 1;
unsigned int happy_count = 0;
while (happy_count != 8)
{
if (is_happy(current_number))
{
std::cout << current_number << " ";
++happy_count;
}
++current_number;
}
std::cout << std::endl;
}

View file

@ -0,0 +1,49 @@
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 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;
}
static void Main(string[] args)
{
int num = 1;
List<int> happynums = new List<int>();
while (happynums.Count < 8)
{
if (ishappy(num))
{
happynums.Add(num);
}
num++;
}
Console.WriteLine("First 8 happy numbers : " + string.Join(",", happynums));
}
}
}

View file

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
class Program
{
static int[] sq = { 1, 4, 9, 16, 25, 36, 49, 64, 81 };
static bool isOne(int x)
{
while (true)
{
if (x == 89) return false;
int s = 0, t;
do if ((t = (x % 10) - 1) >= 0) s += sq[t]; while ((x /= 10) > 0);
if (s == 1) return true;
x = s;
}
}
static void Main(string[] args)
{
const int Max = 10_000_000; DateTime st = DateTime.Now;
Console.Write("---Happy Numbers---\nThe first 8:");
int c = 0, i; for (i = 1; c < 8; i++)
if (isOne(i)) Console.Write("{0} {1}", c == 0 ? "" : ",", i, ++c);
for (int m = 10; m <= Max; m *= 10)
{
Console.Write("\nThe {0:n0}th: ", m);
for (; c < m; i++) if (isOne(i)) c++;
Console.Write("{0:n0}", i - 1);
}
Console.WriteLine("\nComputation time {0} seconds.", (DateTime.Now - st).TotalSeconds);
}
}

View file

@ -0,0 +1,33 @@
#include <stdio.h>
#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};
int happy(int n)
{
int sum = 0, x, nn;
if (n < CACHE) {
if (buf[n]) return 2 - buf[n];
buf[n] = h_no;
}
for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;
x = happy(sum);
if (n < CACHE) buf[n] = 2 - x;
return x;
}
int main()
{
int i, cnt = 8;
for (i = 1; cnt || !printf("\n"); i++)
if (happy(i)) --cnt, printf("%d ", i);
printf("The %dth happy number: ", cnt = 1000000);
for (i = 1; cnt; i++)
if (happy(i)) --cnt || printf("%d\n", i);
return 0;
}

View file

@ -0,0 +1,31 @@
#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("\n"); i++)
if (happy(i)) --cnt, printf("%d ", i);
printf("The %dth happy number: ", cnt = 1000000);
for (i = 1; cnt; i++)
if (happy(i)) --cnt || printf("%d\n", i);
return 0;
}

View file

@ -0,0 +1,36 @@
sum_dig_sq = proc (n: int) returns (int)
sum_sq: int := 0
while n > 0 do
sum_sq := sum_sq + (n // 10) ** 2
n := n / 10
end
return (sum_sq)
end sum_dig_sq
is_happy = proc (n: int) returns (bool)
nn: int := sum_dig_sq(n)
while nn ~= n cand nn ~= 1 do
n := sum_dig_sq(n)
nn := sum_dig_sq(sum_dig_sq(nn))
end
return (nn = 1)
end is_happy
happy_numbers = iter (start, num: int) yields (int)
n: int := start
while num > 0 do
if is_happy(n) then
yield (n)
num := num-1
end
n := n+1
end
end happy_numbers
start_up = proc ()
po: stream := stream$primary_output()
for i: int in happy_numbers(1, 8) do
stream$putl(po, int$unparse(i))
end
end start_up

View file

@ -0,0 +1,56 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. HAPPY.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 CANDIDATE PIC 9(4).
03 SQSUM-IN PIC 9(4).
03 FILLER REDEFINES SQSUM-IN.
05 DIGITS PIC 9 OCCURS 4 TIMES.
03 SQUARE PIC 9(4).
03 SUM-OF-SQUARES PIC 9(4).
03 N PIC 9.
03 TORTOISE PIC 9(4).
03 HARE PIC 9(4).
88 HAPPY VALUE 1.
03 SEEN PIC 9 VALUE ZERO.
03 OUT-FMT PIC ZZZ9.
PROCEDURE DIVISION.
BEGIN.
PERFORM DISPLAY-IF-HAPPY VARYING CANDIDATE FROM 1 BY 1
UNTIL SEEN IS EQUAL TO 8.
STOP RUN.
DISPLAY-IF-HAPPY.
PERFORM CHECK-HAPPY.
IF HAPPY,
MOVE CANDIDATE TO OUT-FMT,
DISPLAY OUT-FMT,
ADD 1 TO SEEN.
CHECK-HAPPY.
MOVE CANDIDATE TO TORTOISE, SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO HARE.
PERFORM CHECK-HAPPY-STEP UNTIL TORTOISE IS EQUAL TO HARE.
CHECK-HAPPY-STEP.
MOVE TORTOISE TO SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO TORTOISE.
MOVE HARE TO SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO SQSUM-IN.
PERFORM CALC-SUM-OF-SQUARES.
MOVE SUM-OF-SQUARES TO HARE.
CALC-SUM-OF-SQUARES.
MOVE ZERO TO SUM-OF-SQUARES.
PERFORM ADD-DIGIT-SQUARE VARYING N FROM 1 BY 1
UNTIL N IS GREATER THAN 4.
ADD-DIGIT-SQUARE.
MULTIPLY DIGITS(N) BY DIGITS(N) GIVING SQUARE.
ADD SQUARE TO SUM-OF-SQUARES.

View file

@ -0,0 +1,15 @@
(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)))))
(def happy-numbers (filter happy? (iterate inc 1)))
(println (take 8 happy-numbers))

View file

@ -0,0 +1,35 @@
(require '[clojure.set :refer [union]])
(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})})
(defn break-apart [n]
(->> (str n)
(map str)
(map #(Long/parseLong %))))
(defn next-number [n]
(->> (break-apart n)
(map #(* % %))
(apply +)))
(defn happy-or-sad? [prev n]
(cond (or (= n 1) ((deref (:happy cache)) n)) :happy
(or ((deref (:sad cache)) n) (some #(= % n) prev)) :sad
:else :unknown))
(defn happy-algo [n]
(let [get-next (fn [[prev n]] [(conj prev n) (next-number n)])
my-happy-or-sad? (fn [[prev n]] [(happy-or-sad? prev n) (conj prev n)])
unknown? (fn [[res nums]] (= res :unknown))
[res nums] (->> [#{} n]
(iterate get-next)
(map my-happy-or-sad?)
(drop-while unknown?)
first)
_ (swap! (res cache) union nums)]
res))
(def happy-numbers (->> (iterate inc 1)
(filter #(= :happy (happy-algo %)))))
(println (take 8 happy-numbers))

View file

@ -0,0 +1,22 @@
happy = (n) ->
seen = {}
while true
n = sum_digit_squares(n)
return true if n == 1
return false if seen[n]
seen[n] = true
sum_digit_squares = (n) ->
sum = 0
for c in n.toString()
d = parseInt(c)
sum += d*d
sum
i = 1
cnt = 0
while cnt < 8
if happy(i)
console.log i
cnt += 1
i += 1

View file

@ -0,0 +1,22 @@
100 C=8:DIM H(145),U(145),N(9)
110 PRINT CHR$(147):PRINT "THE FIRST"C"HAPPY NUMBERS:":PRINT
120 H(1)=1:N=1
130 FOR C=C TO 0 STEP 0
140 : GOSUB 200
150 : IF H THEN PRINT N,:C=C-1
160 : N=N+1
170 NEXT C
180 PRINT
190 END
200 K=0:N(K)=N
210 IF H(N(K)) THEN H=1:FOR J=0 TO K:U(N(J))=0:H(N(J))=1:NEXT J:RETURN
220 IF U(N(K)) THEN H=0:RETURN
230 U(N(K))=1
240 N$=MID$(STR$(N(K)),2)
250 L=LEN(N$)
260 K=K+1:N(K)=0
270 FOR I=1 TO L
280 : D = VAL(MID$(N$,I,1))
290 : N(K) = N(K) + D * D
300 NEXT I
310 GOTO 210

View file

@ -0,0 +1,21 @@
(defun sqr (n)
(* n n))
(defun sum-of-sqr-dgts (n)
(loop for i = n then (floor i 10)
while (plusp i)
sum (sqr (mod i 10))))
(defun happy-p (n &optional cache)
(or (= n 1)
(unless (find n cache)
(happy-p (sum-of-sqr-dgts n)
(cons n cache)))))
(defun happys (&aux (happys 0))
(loop for i from 1
while (< happys 8)
when (happy-p i)
collect i and do (incf happys)))
(print (happys))

View file

@ -0,0 +1,38 @@
include "cowgol.coh";
sub sumDigitSquare(n: uint8): (s: uint8) is
s := 0;
while n != 0 loop
var d := n % 10;
s := s + d * d;
n := n / 10;
end loop;
end sub;
sub isHappy(n: uint8): (h: uint8) is
var seen: uint8[256];
MemZero(&seen[0], @bytesof seen);
while seen[n] == 0 loop
seen[n] := 1;
n := sumDigitSquare(n);
end loop;
if n == 1 then
h := 1;
else
h := 0;
end if;
end sub;
var n: uint8 := 1;
var seen: uint8 := 0;
while seen < 8 loop
if isHappy(n) != 0 then
print_i8(n);
print_nl();
seen := seen + 1;
end if;
n := n + 1;
end loop;

View file

@ -0,0 +1,14 @@
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) }

View file

@ -0,0 +1,23 @@
bool isHappy(int n) pure nothrow {
int[int] past;
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;
}

View file

@ -0,0 +1,19 @@
import std.stdio, std.algorithm, std.range, std.conv, std.string;
bool isHappy(int n) pure nothrow {
int[int] seen;
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;
}

View file

@ -0,0 +1,50 @@
$ 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
$ j = j + 1
$ goto loop5
$ continue:
$ i = i + 1
$ goto loop1
$ done:
$ show symbol found*

View file

@ -0,0 +1,30 @@
function IsHappy(n : Integer) : Boolean;
var
cache : array of Integer;
sum : Integer;
begin
while True do begin
sum := 0;
while n>0 do begin
sum += Sqr(n mod 10);
n := n div 10;
end;
if sum = 1 then
Exit(True);
if sum in cache then
Exit(False);
n := sum;
cache.Add(sum);
end;
end;
var n := 8;
var i : Integer;
while n>0 do begin
Inc(i);
if IsHappy(i) then begin
PrintLn(i);
Dec(n);
end;
end;

View file

@ -0,0 +1,35 @@
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++;
}
}

View file

@ -0,0 +1,4 @@
[lcI~rscd*+lc0<H]sH
[0rsclHxd4<h]sh
[lIp]s_
0sI[lI1+dsIlhx2>_z8>s]dssx

View file

@ -0,0 +1,64 @@
program Happy_numbers;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Int;
type
TIntegerDynArray = TArray<Integer>;
TIntHelper = record helper for Integer
function IsHappy: Boolean;
procedure Next;
end;
{ TIntHelper }
function TIntHelper.IsHappy: Boolean;
var
cache: TIntegerDynArray;
sum, n: integer;
begin
n := self;
repeat
sum := 0;
while n > 0 do
begin
sum := sum + (n mod 10) * (n mod 10);
n := n div 10;
end;
if sum = 1 then
exit(True);
if cache.Has(sum) then
exit(False);
n := sum;
cache.Add(sum);
until false;
end;
procedure TIntHelper.Next;
begin
inc(self);
end;
var
count, n: integer;
begin
n := 1;
count := 0;
while count < 8 do
begin
if n.IsHappy then
begin
count.Next;
write(n, ' ');
end;
n.Next;
end;
writeln;
readln;
end.

View file

@ -0,0 +1,34 @@
proc nonrec dsumsq(byte n) byte:
byte r, d;
r := 0;
while n~=0 do
d := n % 10;
n := n / 10;
r := r + d * d
od;
r
corp
proc nonrec happy(byte n) bool:
[256] bool seen;
byte i;
for i from 0 upto 255 do seen[i] := false od;
while not seen[n] do
seen[n] := true;
n := dsumsq(n)
od;
seen[1]
corp
proc nonrec main() void:
byte n, seen;
n := 1;
seen := 0;
while seen < 8 do
if happy(n) then
writeln(n:3);
seen := seen + 1
fi;
n := n + 1
od
corp

View file

@ -0,0 +1,27 @@
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
}
var (n, found) = (1, 0)
while found < 8 {
if happy(n) {
print("\(n) ", terminator: "")
found += 1
}
n += 1
}
print()

View file

@ -0,0 +1,20 @@
def isHappyNumber(var x :int) {
var seen := [].asSet()
while (!seen.contains(x)) {
seen with= x
var sum := 0
while (x > 0) {
sum += (x % 10) ** 2
x //= 10
}
x := sum
if (x == 1) { return true }
}
return false
}
var count := 0
for x ? (isHappyNumber(x)) in (int >= 1) {
println(x)
if ((count += 1) >= 8) { break }
}

View file

@ -0,0 +1,70 @@
class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
local
l_val: INTEGER
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
feature -- Happy number
is_happy_number (a_number: INTEGER): BOOLEAN
-- Is `a_number' a happy number?
require
positive_number: a_number > 0
local
l_number: INTEGER
l_set: ARRAYED_SET [INTEGER]
do
from
l_number := a_number
create l_set.make (10)
until
l_number = 1 or l_set.has (l_number)
loop
l_set.put (l_number)
l_number := square_sum_of_digits (l_number)
end
Result := (l_number = 1)
end
feature{NONE} -- Implementation
square_sum_of_digits (a_number: INTEGER): INTEGER
-- Sum of the sqares of digits of `a_number'.
require
positive_number: a_number > 0
local
l_number, l_digit: INTEGER
do
from
l_number := a_number
until
l_number = 0
loop
l_digit := l_number \\ 10
Result := Result + l_digit * l_digit
l_number := l_number // 10
end
end
end

View file

@ -0,0 +1,44 @@
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
};
console.printLine("First 8 happy numbers: ", happynums.asEnumerable())
}

View file

@ -0,0 +1,27 @@
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
defp square_sum(0, sum), do: sum
defp square_sum(n, sum) do
r = rem(n, 10)
square_sum(div(n, 10), sum + r*r)
end
end
IO.inspect Happy.task(8)

View file

@ -0,0 +1,32 @@
-module(tasks).
-export([main/0]).
-import(lists, [map/2, member/2, sort/1, sum/1]).
is_happy(X, XS) ->
if
X == 1 ->
true;
X < 1 ->
false;
true ->
case member(X, XS) of
true -> false;
false ->
is_happy(sum(map(fun(Z) -> Z*Z end,
[Y - 48 || Y <- integer_to_list(X)])),
[X|XS])
end
end.
main(X, XS) ->
if
length(XS) == 8 ->
io:format("8 Happy Numbers: ~w~n", [sort(XS)]);
true ->
case is_happy(X, []) of
true -> main(X + 1, [X|XS]);
false -> main(X + 1, XS)
end
end.
main() ->
main(0, []).

View file

@ -0,0 +1 @@
erl -run tasks main -run init stop -noshell

View file

@ -0,0 +1 @@
8 Happy Numbers: [1,7,10,13,19,23,28,31]

View file

@ -0,0 +1,18 @@
-module(tasks).
-export([main/0]).
main() -> io:format("~w ~n", [happy_list(1, 8, [])]).
happy_list(_, N, L) when length(L) =:= N -> lists:reverse(L);
happy_list(X, N, L) ->
Happy = is_happy(X),
if Happy -> happy_list(X + 1, N, [X|L]);
true -> happy_list(X + 1, N, L) end.
is_happy(1) -> true;
is_happy(4) -> false;
is_happy(N) when N > 0 ->
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.

View file

@ -0,0 +1,29 @@
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

View file

@ -0,0 +1,29 @@
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.Structural) // Set to keep cycle values in
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.iter (fun i -> dict.[i] <- f) // and apply it to all the values in the cycle
f // Return the boolean
1 // Starting with 1,
|> Seq.unfold (fun i -> Some (i, i + 1)) // make an infinite sequence of consecutive integers
|> Seq.filter IsHappy // Keep only the happy ones
|> Seq.truncate 8 // Stop when we've found 8
|> Seq.iter (Printf.printf "%d\n") // Print results

View file

@ -0,0 +1,15 @@
[$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}
{check happy number}
[
$1[f;!~2ø1=~&][1+\s;!@]# {loop over sequence until 1 or duplicate}
1ø1= {return value}
\[$0=~][@%1-]#% {drop sequence and counter}
]h:
0 1
"Happy numbers:"
[1ø8=~][h;![" "$.\1+\]?1+]#
%%

View file

@ -0,0 +1,19 @@
01.10 S J=0;S N=1;T %2
01.20 D 3;I (K-2)1.5
01.30 S N=N+1
01.40 I (J-8)1.2;Q
01.50 T N,!
01.60 S J=J+1
01.70 G 1.3
02.10 S A=K;S R=0
02.20 S B=FITR(A/10)
02.30 S R=R+(A-10*B)^2
02.40 S A=B
02.50 I (-A)2.2
03.10 F X=0,162;S S(X)=-1
03.20 S K=N
03.30 S S(K)=0
03.40 D 2;S K=R
03.50 I (S(K))3.3

View file

@ -0,0 +1,21 @@
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 ;

View file

@ -0,0 +1 @@
8 happy-numbers ! { 1 7 10 13 19 23 28 31 }

View file

@ -0,0 +1,35 @@
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)
}
public static Void main ()
{
i := 1
count := 0
while (count < 8)
{
if (isHappy (i))
{
echo (i)
count += 1
}
i += 1
}
}
}

View file

@ -0,0 +1,20 @@
: 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

View file

@ -0,0 +1,10 @@
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

View file

@ -0,0 +1,5 @@
: 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

View file

@ -0,0 +1,67 @@
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
function sum_digits_squared (number) result (result)
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
end function sum_digits_squared
function is_happy (number) result (result)
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
end function is_happy
end program happy

View file

@ -0,0 +1,44 @@
' FB 1.05.0 Win64
Function isHappy(n As Integer) As Boolean
If n < 0 Then Return False
' Declare a dynamic array to store previous sums.
' If a previous sum is duplicated before a sum of 1 is reached
' then the number can't be "happy" as the cycle will just repeat
Dim prevSums() As Integer
Dim As Integer digit, ub, sum = 0
Do
While n > 0
digit = n Mod 10
sum += digit * digit
n \= 10
Wend
If sum = 1 Then Return True
ub = UBound(prevSums)
If ub > -1 Then
For i As Integer = 0 To ub
If sum = prevSums(i) Then Return False
Next
End If
ub += 1
Redim Preserve prevSums(0 To ub)
prevSums(ub) = sum
n = sum
sum = 0
Loop
End Function
Dim As Integer n = 1, count = 0
Print "The first 8 happy numbers are : "
Print
While count < 8
If isHappy(n) Then
count += 1
Print count;" =>"; n
End If
n += 1
Wend
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,17 @@
module Happy where
import Prelude.Math
-- ugh, since Frege doesn't have Set, use Map instead
import Data.Map (member, insertMin, empty emptyMap)
digitToInteger :: Char -> Integer
digitToInteger c = fromInt $ (ord c) - (ord '0')
isHappy :: Integer -> Bool
isHappy = p emptyMap
where p _ 1n = true
p s n | n `member` s = false
| otherwise = p (insertMin n () s) (f n)
f = sum . map (sqr . digitToInteger) . unpacked . show
main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n

View file

@ -0,0 +1,30 @@
include "NSLog.incl"
local fn IsHappy( num as NSUInteger ) as NSUInteger
NSUInteger i, happy = 0, count = 0
while ( count < 50 ) and ( happy != 1 )
CFStringRef numStr = str( num )
count++ : happy = 0
for i = 1 to len( numStr )
happy = happy + fn StringIntegerValue( mid( numStr, i, 1 ) ) ^ 2
next
num = happy
wend
end fn = num
void local fn HappyNumbers
NSUInteger i, count = 0
for i = 1 to 100
if ( fn IsHappy(i) == 1 )
count++
NSLog( @"%2lu. %2lu is a happy number", count, i )
if count == 8 then exit fn
end if
next
end fn
fn HappyNumbers
HandleEvents

View file

@ -0,0 +1,29 @@
package main
import "fmt"
func happy(n int) bool {
m := make(map[int]bool)
for n > 1 {
m[n] = true
var x int
for x, n = n, 0; x > 0; x /= 10 {
d := x % 10
n += d * d
}
if m[n] {
return false
}
}
return true
}
func main() {
for found, n := 0, 1; found < 8; n++ {
if happy(n) {
fmt.Print(n, " ")
found++
}
}
fmt.Println()
}

View file

@ -0,0 +1,15 @@
Number.metaClass.isHappy = {
def number = delegate as Long
def cycle = new HashSet<Long>()
while (number != 1 && !cycle.contains(number)) {
cycle << number
number = (number as String).collect { d = (it as Long); d * d }.sum()
}
number == 1
}
def matches = []
for (int i = 0; matches.size() < 8; i++) {
if (i.happy) { matches << i }
}
println matches

View file

@ -0,0 +1,33 @@
PROCEDURE Main()
LOCAL i := 8, nH := 0
? hb_StrFormat( "The first %d happy numbers are:", i )
?
WHILE i > 0
IF IsHappy( ++nH )
?? hb_NtoS( nH ) + " "
--i
ENDIF
END
RETURN
STATIC FUNCTION IsHappy( nNumber )
STATIC aUnhappy := {}
LOCAL nDigit, nSum := 0, cNumber := hb_NtoS( nNumber )
FOR EACH nDigit IN cNumber
nSum += Val( nDigit ) ^ 2
NEXT
IF nSum == 1
aUnhappy := {}
RETURN .T.
ELSEIF AScan( aUnhappy, nSum ) > 0
RETURN .F.
ENDIF
AAdd( aUnhappy, nSum )
RETURN IsHappy( nSum )

View file

@ -0,0 +1,14 @@
import Data.Char (digitToInt)
import Data.Set (member, insert, empty)
isHappy :: Integer -> Bool
isHappy = p empty
where
p _ 1 = True
p s n
| n `member` s = False
| otherwise = p (insert n s) (f n)
f = sum . fmap ((^ 2) . toInteger . digitToInt) . show
main :: IO ()
main = mapM_ print $ take 8 $ filter isHappy [1 ..]

View file

@ -0,0 +1,19 @@
import Data.Array (Array, (!), listArray)
happy :: Int -> Bool
happy x
| xx <= 150 = seen ! xx
| otherwise = happy xx
where
xx = dsum x
seen :: Array Int Bool
seen =
listArray (1, 150) $ True : False : False : False : (happy <$> [5 .. 150])
dsum n
| n < 10 = n * n
| otherwise =
let (q, r) = n `divMod` 10
in r * r + dsum q
main :: IO ()
main = print $ sum $ take 10000 $ filter happy [1 ..]

View file

@ -0,0 +1,17 @@
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
procedure happy(i) #: returns i if i is happy
local n
if 4 ~= (0 <= i) then { # unhappy if negative, 0, or 4
if i = 1 then return i
every (n := 0) +:= !i ^ 2
if happy(n) then return i
}
end

View file

@ -0,0 +1,2 @@
8{. (#~1=+/@(*:@(,.&.":))^:(1&~:*.4&~:)^:_ "0) 1+i.100
1 7 10 13 19 23 28 31

View file

@ -0,0 +1 @@
f ^: cond ^: _ input

View file

@ -0,0 +1 @@
(binary array) # 1..100

View file

@ -0,0 +1,7 @@
cond=: 1&~: *. 4&~: NB. not equal to 1 and not equal to 4
sumSqrDigits=: +/@(*:@(,.&.":))
sumSqrDigits 123 NB. test sum of squared digits
14
8{. (#~ 1 = sumSqrDigits ^: cond ^:_ "0) 1 + i.100
1 7 10 13 19 23 28 31

View file

@ -0,0 +1,27 @@
import java.util.HashSet;
public class Happy{
public static boolean happy(long number){
long m = 0;
int digit = 0;
HashSet<Long> cycle = new HashSet<Long>();
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;
}
public static void main(String[] args){
for(long num = 1,count = 0;count<8;num++){
if(happy(num)){
System.out.println(num);
count++;
}
}
}
}

View file

@ -0,0 +1,26 @@
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class HappyNumbers {
public static void main(String[] args) {
for (int current = 1, total = 0; total < 8; current++)
if (isHappy(current)) {
System.out.println(current);
total++;
}
}
public static boolean isHappy(int number) {
HashSet<Integer> cycle = new HashSet<>();
while (number != 1 && cycle.add(number)) {
List<String> numStrList = Arrays.asList(String.valueOf(number).split(""));
number = numStrList.stream().map(i -> Math.pow(Integer.parseInt(i), 2)).mapToInt(i -> i.intValue()).sum();
}
return number == 1;
}
}

View file

@ -0,0 +1,26 @@
function happy(number) {
var m, digit ;
var cycle = [] ;
while(number != 1 && cycle[number] !== true) {
cycle[number] = true ;
m = 0 ;
while (number > 0) {
digit = number % 10 ;
m += digit * digit ;
number = (number - digit) / 10 ;
}
number = m ;
}
return (number == 1) ;
}
var cnt = 8 ;
var number = 1 ;
while(cnt-- > 0) {
while(!happy(number))
number++ ;
document.write(number + " ") ;
number++ ;
}

View file

@ -0,0 +1,60 @@
(() => {
// isHappy :: Int -> Bool
const isHappy = n => {
const f = n =>
foldl(
(a, x) => a + raise(read(x), 2), // ^2
0,
splitOn('', show(n))
),
p = (s, n) => n === 1 ? (
true
) : member(n, s) ? (
false
) : p(
insert(n, s), f(n)
);
return p(new Set(), n);
};
// GENERIC FUNCTIONS ------------------------------------------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// insert :: Ord a => a -> Set a -> Set a
const insert = (e, s) => s.add(e);
// member :: Ord a => a -> Set a -> Bool
const member = (e, s) => s.has(e);
// read :: Read a => String -> a
const read = JSON.parse;
// show :: a -> String
const show = x => JSON.stringify(x);
// splitOn :: String -> String -> [String]
const splitOn = (cs, xs) => xs.split(cs);
// raise :: Num -> Int -> Num
const raise = (n, e) => Math.pow(n, e);
// take :: Int -> [a] -> [a]
const take = (n, xs) => xs.slice(0, n);
// TEST -------------------------------------------------------------------
return show(
take(8, filter(isHappy, enumFromTo(1, 50)))
);
})()

View file

@ -0,0 +1 @@
[1, 7, 10, 13, 19, 23, 28, 31]

View file

@ -0,0 +1,71 @@
(() => {
// isHappy :: Int -> Bool
const isHappy = n => {
const f = n =>
foldl(
(a, x) => a + raise(read(x), 2), // ^2
0,
splitOn('', show(n))
),
p = (s, n) => n === 1 ? (
true
) : member(n, s) ? (
false
) : p(
insert(n, s), f(n)
);
return p(new Set(), n);
};
// GENERIC FUNCTIONS ------------------------------------------------------
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// insert :: Ord a => a -> Set a -> Set a
const insert = (e, s) => s.add(e);
// member :: Ord a => a -> Set a -> Bool
const member = (e, s) => s.has(e);
// read :: Read a => String -> a
const read = JSON.parse;
// show :: a -> String
const show = x => JSON.stringify(x);
// splitOn :: String -> String -> [String]
const splitOn = (cs, xs) => xs.split(cs);
// raise :: Num -> Int -> Num
const raise = (n, e) => Math.pow(n, e);
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// 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
);
})();

View file

@ -0,0 +1 @@
[1, 7, 10, 13, 19, 23, 28, 31]

View file

@ -0,0 +1,15 @@
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 );

View file

@ -0,0 +1,12 @@
# Set n to -1 to continue indefinitely:
def happy(n):
def subtask: # state: [i, found]
if .[1] == n then empty
else .[0] as $n
| if ($n | is_happy_number) then $n, ([ $n+1, .[1]+1 ] | subtask)
else (.[0] += 1) | subtask
end
end;
[0,0] | subtask;
happy($n|tonumber)

View file

@ -0,0 +1,9 @@
$ jq --arg n 8 -n -f happy.jq
1
7
10
13
19
23
28
31

View file

@ -0,0 +1,15 @@
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

View file

@ -0,0 +1,11 @@
sumhappy(n) = sum(x->x^2, digits(n))
function ishappy(x, mem = [])
x == 1? true :
x in mem? false :
ishappy(sumhappy(x),[mem ; x])
end
nexthappy (x) = ishappy(x+1) ? x+1 : nexthappy(x+1)
happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-1]]

Some files were not shown because too many files have changed in this diff Show more