1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators kernel make math ;
4 IN: rosetta-code.happy-numbers
6 ! http://rosettacode.org/wiki/Happy_numbers#Factor
8 ! From Wikipedia, the free encyclopedia:
10 ! A happy number is defined by the following process. Starting
11 ! with any positive integer, replace the number by the sum of the
12 ! squares of its digits, and repeat the process until the number
13 ! equals 1 (where it will stay), or it loops endlessly in a cycle
14 ! which does not include 1. Those numbers for which this process
15 ! ends in 1 are happy numbers, while those that do not end in 1
16 ! are unhappy numbers. Display an example of your output here.
18 ! Task: Find and print the first 8 happy numbers.
21 0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;
23 : (happy?) ( n1 n2 -- ? )
24 [ squares ] [ squares squares ] bi* {
25 { [ dup 1 = ] [ 2drop t ] }
26 { [ 2dup = ] [ 2drop f ] }
33 : happy-numbers ( n -- seq )
36 dup happy? [ dup , [ 1 - ] dip ] when 1 +