New module math.primes.factors

db4
Samuel Tardieu 2007-12-27 15:03:22 +01:00
parent 694dd297ad
commit e17a77f5cd
5 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1 @@
Samuel Tardieu

View File

@ -0,0 +1,20 @@
USING: help.markup help.syntax ;
IN: math.primes.factors
{ factors count-factors unique-factors } related-words
HELP: factors
{ $values { "n" "a positive integer" } { "seq" "a sequence" } }
{ $description { "Factorize an integer and return an ordered list of factors, possibly repeated." } } ;
HELP: count-factors
{ $values { "n" "a positive integer" } { "seq" "a sequence" } }
{ $description { "Return a sequence of pairs representing each factor in the number and its corresponding power." } } ;
HELP: unique-factors
{ $values { "n" "a positive integer" } { "seq" "a sequence" } }
{ $description { "Return an ordered list of unique prime factors." } } ;
HELP: totient
{ $values { "n" "a positive integer" } { "t" "an integer" } }
{ $description { "Return the number of integers between 1 and " { $snippet "n-1" } " relatively prime to " { $snippet "n" } "." } } ;

View File

@ -0,0 +1,6 @@
USING: math.primes.factors tools.test ;
{ { 999983 999983 1000003 } } [ 999969000187000867 factors ] unit-test
{ { { 999983 2 } { 1000003 1 } } } [ 999969000187000867 count-factors ] unit-test
{ { 999983 1000003 } } [ 999969000187000867 unique-factors ] unit-test
{ 999967000236000612 } [ 999969000187000867 totient ] unit-test

View File

@ -0,0 +1,41 @@
! Copyright (C) 2007 Samuel Tardieu.
! See http://factorcode.org/license.txt for BSD license.
USING: arrays kernel lazy-lists math math.primes namespaces sequences ;
IN: math.primes.factors
<PRIVATE
: (factor) ( n d -- n' )
2dup mod zero? [ [ / ] keep dup , (factor) ] [ drop ] if ;
: (count) ( n d -- n' )
[ (factor) ] { } make
dup empty? [ drop ] [ [ first ] keep length 2array , ] if ;
: (unique) ( n d -- n' )
[ (factor) ] { } make
dup empty? [ drop ] [ first , ] if ;
: (factors) ( quot list n -- )
dup 1 > [ swap uncons >r pick call r> swap (factors) ] [ 3drop ] if ;
: (decompose) ( n quot -- seq )
[ lprimes rot (factors) ] { } make ;
PRIVATE>
: factors ( n -- seq )
[ (factor) ] (decompose) ; foldable
: count-factors ( n -- seq )
[ (count) ] (decompose) ; foldable
: unique-factors ( n -- seq )
[ (unique) ] (decompose) ; foldable
: totient ( n -- t )
dup 2 < [
drop 0
] [
[ unique-factors dup 1 [ 1- * ] reduce swap product / ] keep *
] if ; foldable

View File

@ -0,0 +1 @@
Prime factors decomposition