]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/happy-numbers/happy-numbers.factor
factor: trim using lists
[factor.git] / extra / rosetta-code / happy-numbers / happy-numbers.factor
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
5
6 ! http://rosettacode.org/wiki/Happy_numbers#Factor
7
8 ! From Wikipedia, the free encyclopedia:
9
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.
17
18 ! Task: Find and print the first 8 happy numbers.
19
20 : squares ( n -- s )
21     0 [ over 0 > ] [ [ 10 /mod sq ] dip + ] while nip ;
22
23 : (happy?) ( n1 n2 -- ? )
24     [ squares ] [ squares squares ] bi* {
25         { [ dup 1 = ] [ 2drop t ] }
26         { [ 2dup = ] [ 2drop f ] }
27         [ (happy?) ]
28     } cond ;
29
30 : happy? ( n -- ? )
31     dup (happy?) ;
32
33 : happy-numbers ( n -- seq )
34     [
35         0 [ over 0 > ] [
36             dup happy? [ dup , [ 1 - ] dip ] when 1 +
37         ] while 2drop
38     ] { } make ;