Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers.

: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")elseset max=%min%::The FOR /L loop does not detect integer overflow, so must protect against::an infinite loop when max=0x7FFFFFFFFset end=%max%if%end%equ 2147483647 set /a end-=1for /l %%Nin(%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-=1if!cnt!leq 0 exit /b 0)if!n!equ 2147483647 (>&2 echo ERROR: Maximum integer value reachedexit /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.setlocalset n=%1for%%. in(%L10%%L10%%L10%)do(if!n!==1 exit /b 0%= Only numbers < 1000 can cycle =%if!n!lss 1000 (ifdefined t.!n!exit /b 1set 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=0for /l %%Nin(1 1 10)do(if!n!gtr 0 set /a "sum+=(n%%10)*(n%%10), n/=10")set /a n=sum)

This example does not show the output mentioned in the task description on this page (or a page linked to from here). Please ensure that it meets all task requirements and remove this message. Note that phrases in task descriptions such as "print and display" and "print and show" for example, indicate that (reasonable length) output be a part of a language's solution.

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.truncate8// Stop when we've found 8|>Seq.iter(Printf.printf"%d\n")// Print results

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.

BTW Calculate the next number using the happy formulaHOW IZ I HAPPYSTEP YR NUMI HAS A NEXT ITZ0IMINYRLOOPBOTH SAEM NUM AN0O RLY? YA RLYGTFO OICI HAS A DIGIT ITZMODOF NUM AN10 NUM RQUOSHUNTOF NUM AN10I HAS A SQUARE ITZPRODUKTOF DIGIT AN DIGIT NEXT RSUMOF NEXT AN SQUAREIMOUTTAYRLOOPFOUND YR NEXTIF U SAY SO

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.)

(*A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here.*)

ISHAPPY(N) ;Determines if a number N is a happy number ;Note that the returned strings do not have a leading digit unless it is a happy number IF (N'=N\1)!(N<0) QUIT "Not a positive integer" NEW SUM,I ;SUM is the sum of the square of each digit ;I is a loop variable ;SEQ is the sequence of previously checked SUMs from the original N ;If it isn't set already, initialize it to an empty string IF $DATA(SEQ)=0 NEW SEQ SET SEQ="" SET SUM=0 FOR I=1:1:$LENGTH(N) DO .SET SUM=SUM+($EXTRACT(N,I)*$EXTRACT(N,I)) QUIT:(SUM=1) SUM QUIT:$FIND(SEQ,SUM)>1 "Part of a sequence not containing 1" SET SEQ=SEQ_","_SUM QUIT $$ISHAPPY(SUM)HAPPY(C) ;Finds the first C happy numbers NEW I ;I is a counter for what integer we're looking at WRITE !,"The first "_C_" happy numbers are:" FOR I=1:1 QUIT:C<1 SET Q=+$$ISHAPPY(I) WRITE:Q !,I SET:Q C=C-1 KILL I QUIT

-- use to trace previous cycle results previous = .set~newloopforever-- stop when we hit the targetif number = 1thenreturn.true-- stop as soon as we start cyclingif previous[number]\== .nil thenreturn.false previous~put(number) next = 0-- loop over all of the digitsloop digit over number~makearray('') next += digit * digitend-- and repeat the cycle number = nextend

This example does not show the output mentioned in the task description on this page (or a page linked to from here). Please ensure that it meets all task requirements and remove this message. Note that phrases in task descriptions such as "print and display" and "print and show" for example, indicate that (reasonable length) output be a part of a language's solution.

This code uses the select() function, which was added in PARI version 2.4.2. The order of the arguments changed between versions; to use in 2.4.2 change select(function, vector) to select(vector, function).

If the number has more than three digits, the sum of the squares of its digits has fewer digits than the number itself. If the number has three digits, the sum of the squares of its digits is at most 3 * 9^2 = 243. A simple solution is to look up numbers up to 243 and calculate the sum of squares only for larger numbers.

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.

function is_happy(integer n)sequence seen = {}integer k while n>1 do seen &= n k = 0 while n>0 do k += power(remainder(n,10),2) n = floor(n/10) end while n = k if find(n,seen) then return 0 end if end while return 1end function

/*REXX program computes and displays a specified amount of happy numbers. */parsearg limit ./*obtain optional argument from the CL.*/if limit==''| limit==","then limit=8/*Not specified? Then use the default.*/haps=0/*count of the happy numbers (so far).*/

do n=1while haps<limit; @.=0; q=n /*search the integers starting at unity*/dountil q==1/*determine if Q is a happy number.*/ s=0/*prepare to add squares of digits. */do j=1forlength(q)/*sum the squares of the decimal digits*/ s=s + substr(q, j, 1)**2/*add the square of a decimal digit.*/end/*j*/

const func boolean: happy (in var integer: number) is func result var boolean: isHappy is FALSE; local var bitset: cycle is bitset.value; var integer: newnumber is 0; var integer: cycleNum is 0; begin while number > 1 and number not in cycle do if number in cache then number := ord(cache[number]); else incl(cycle, number); newnumber := 0; while number > 0 do newnumber +:= (number rem 10) ** 2; number := number div 10; end while; number := newnumber; end if; end while; isHappy := number = 1; for cycleNum range cycle do cache @:= [cycleNum] isHappy; end for; end func;

const proc: main is func local var integer: number is 0; begin for number range 1 to 50 do if happy(number) then writeln(number); end if; end for; end func;

The largest possible 32-bit integer is less than 9,999,999,999. The sum of
the squares of these ten digits is 10*9^2 = 810. If a cycle consisted of all
the values smaller than 810, an array size of 810 would still be sufficiently
large to hold them. Actually, tests show that the array only needs to hold 16
numbers.

int List(810); \list of numbers in a cycleint Inx; \index for Listinclude c:\cxpl\codes;

func HadNum(N); \Return 'true' if number N is in the Listint N;int I;[for I:= 0 to Inx-1 do if N = List(I) then return true;return false;]; \HadNum

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).