]> gitweb.factorcode.org Git - factor.git/blob - basis/math/primes/factors/factors.factor
factor: Move math.ranges => ranges.
[factor.git] / basis / math / primes / factors / factors.factor
1 ! Copyright (C) 2007-2009 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays combinators command-line io kernel math
4 math.functions math.parser math.primes.pollard-rho-brent
5 ranges math.statistics namespaces sequences
6 sequences.product sets sorting splitting ;
7 IN: math.primes.factors
8
9 : factors ( n -- seq ) pollard-rho-brent-factors ; flushable
10
11 : group-factors ( n -- seq ) factors histogram sort-keys ; flushable
12
13 : unique-factors ( n -- seq ) factors members ; flushable
14
15 : totient ( n -- t )
16     {
17         { [ dup 2 < ] [ drop 0 ] }
18         [ dup unique-factors [ 1 [ 1 - * ] reduce ] [ product ] bi / * ]
19     } cond ; foldable
20
21 : divisors ( n -- seq )
22     dup 1 = [
23         1array
24     ] [
25         group-factors dup empty? [
26             [ first2 [0..b] [ ^ ] with map ] map
27             [ product ] product-map natural-sort
28         ] unless
29     ] if ;
30
31 : unix-factor ( string -- )
32     dup string>number [
33         [ ": " append write ]
34         [ factors [ number>string ] map join-words print ] bi*
35     ] [
36         "factor: `" "' is not a valid positive integer" surround print
37     ] if* flush ;
38
39 : run-unix-factor ( -- )
40     command-line get [
41         [ readln [ unix-factor t ] [ f ] if* ] loop
42     ] [
43         [ unix-factor ] each
44     ] if-empty ;
45
46 MAIN: run-unix-factor