2007-12-27 09:03:22 -05:00
|
|
|
! Copyright (C) 2007 Samuel Tardieu.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2008-09-10 23:11:40 -04:00
|
|
|
USING: arrays kernel lists math math.primes namespaces make
|
|
|
|
sequences ;
|
2007-12-27 09:03:22 -05:00
|
|
|
IN: math.primes.factors
|
|
|
|
|
|
|
|
<PRIVATE
|
|
|
|
|
|
|
|
: (factor) ( n d -- n' )
|
2008-01-14 02:38:23 -05:00
|
|
|
2dup mod zero? [ [ / ] keep dup , (factor) ] [ drop ] if ;
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
: (count) ( n d -- n' )
|
2008-01-14 02:38:23 -05:00
|
|
|
[ (factor) ] { } make
|
2008-09-06 18:15:25 -04:00
|
|
|
[ [ first ] keep length 2array , ] unless-empty ;
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
: (unique) ( n d -- n' )
|
2008-01-14 02:38:23 -05:00
|
|
|
[ (factor) ] { } make
|
2008-09-06 18:15:25 -04:00
|
|
|
[ first , ] unless-empty ;
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
: (factors) ( quot list n -- )
|
2008-06-03 05:06:52 -04:00
|
|
|
dup 1 > [ swap uncons swap >r pick call r> swap (factors) ] [ 3drop ] if ;
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
: (decompose) ( n quot -- seq )
|
2008-01-14 02:38:23 -05:00
|
|
|
[ lprimes rot (factors) ] { } make ;
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
PRIVATE>
|
|
|
|
|
|
|
|
: factors ( n -- seq )
|
2008-01-14 02:38:23 -05:00
|
|
|
[ (factor) ] (decompose) ; foldable
|
2007-12-27 09:03:22 -05:00
|
|
|
|
2008-01-14 11:33:08 -05:00
|
|
|
: group-factors ( n -- seq )
|
2008-01-14 02:38:23 -05:00
|
|
|
[ (count) ] (decompose) ; foldable
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
: unique-factors ( n -- seq )
|
2008-01-14 02:38:23 -05:00
|
|
|
[ (unique) ] (decompose) ; foldable
|
2007-12-27 09:03:22 -05:00
|
|
|
|
|
|
|
: totient ( n -- t )
|
2008-01-14 02:38:23 -05:00
|
|
|
dup 2 < [
|
|
|
|
drop 0
|
|
|
|
] [
|
|
|
|
dup unique-factors dup 1 [ 1- * ] reduce swap product / *
|
|
|
|
] if ; foldable
|