#!/usr/bin/env setl
--
-- Happy numbers in SETL.
--
-- From http://rosettacode.org/wiki/Happy_numbers
-- """
-- From Wikipedia, the free encyclopedia:
--
-- 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.
--
-- Task: Find and print the first 8 happy numbers.
-- """
--
-- The answer is: 1 7 10 13 19 23 28 31
--
-- Also, see http://en.wikipedia.org/wiki/Happy_number
--
-- This SETL program was created by Hakan Kjellerstrand (hakank@bonetmail.com)
-- Also see my SETL page: http://www.hakank.org/setl/
--
num_happy := 0;
happy := [];
n := 1;
until #happy = 8 loop
if is_happy(n) then happy with:= n; end if;
n +:= 1;
end loop;
print("HAPPY:", happy);
-- The happy numbers <= 100
print(h := [n : n in [1..100] | is_happy(n)]);
--
-- is n a happy number?
--
proc is_happy(n);
s := [n];
while n > 1 loop
if (n := +/[val(i)**2: i in str(n)]) in s then
return false;
end if;
s with:= n;
end while;
return true;
end proc;