factor/basis/math/primes/factors/factors.factor

43 lines
1.2 KiB
Factor
Raw Normal View History

! Copyright (C) 2007-2009 Samuel Tardieu.
2007-12-27 09:03:22 -05:00
! See http://factorcode.org/license.txt for BSD license.
2009-01-07 16:16:39 -05:00
USING: arrays combinators kernel make math math.primes sequences ;
2007-12-27 09:03:22 -05:00
IN: math.primes.factors
<PRIVATE
: count-factor ( n d -- n' c )
2009-01-07 16:16:39 -05:00
[ 1 ] 2dip [ /i ] keep
[ dupd /mod zero? ] curry [ nip [ 1+ ] dip ] while drop
2009-01-07 16:16:39 -05:00
swap ;
: write-factor ( n d -- n' d' )
2dup mod zero? [
[ [ count-factor ] keep swap 2array , ] keep
! If the remainder is a prime number, increase d so that
! the caller stops looking for factors.
over prime? [ drop dup ] when
] when ;
: (group-factors) ( n -- seq )
2009-02-02 18:33:04 -05:00
[
2
[ 2dup sq < ] [ write-factor next-prime ] until
2009-02-02 18:33:04 -05:00
drop dup 2 < [ drop ] [ 1 2array , ] if
] { } make ;
2007-12-27 09:03:22 -05:00
PRIVATE>
: group-factors ( n -- seq )
dup prime? [ 1 2array 1array ] [ (group-factors) ] if ; flushable
: unique-factors ( n -- seq ) group-factors [ first ] map ; flushable
2007-12-27 09:03:22 -05:00
: factors ( n -- seq )
group-factors [ first2 swap <array> ] map concat ; flushable
2007-12-27 09:03:22 -05:00
: totient ( n -- t )
2009-01-07 16:16:39 -05:00
{
{ [ dup 2 < ] [ drop 0 ] }
[ dup unique-factors [ 1 [ 1- * ] reduce ] [ product ] bi / * ]
} cond ; foldable