Sunday, 21 November 2010

Just for the fun of it: Happy Numbers

Here's an Applescript that determines whether a given number is a Happy Number. The script returns the final verdict (true or false) and the sequence of the sums of squares that led to that verdict.


(* 
HappyNumbers.scpt
This script determines whether a number is happy or not
http://en.wikipedia.org/wiki/Happy_number
*)

display dialog "Enter any integer number" default answer 2 buttons {"OK"} default button {"OK"}
set k to text returned of result

set s to {}

repeat while k is not (1)
set sq to 0
-- determine the sum of squares of the digits
repeat with i from 1 to count of (k as text)
set sq to sq + (item i of (k as text)) ^ 2
end repeat
set k to (sq as integer)
-- if the result already occured: we're in a loop
if k is in s then
say "Unhappy"
return {false, s}
end if
-- remember the result
set end of s to k
end repeat
say "Happy"
return {true, s}

No comments: