]> gitweb.factorcode.org Git - factor.git/blob - basis/math/primes/primes.factor
Merge branch 'master' into redis
[factor.git] / basis / math / primes / primes.factor
1 ! Copyright (C) 2007-2009 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators kernel math math.bitwise math.functions
4 math.order math.primes.erato math.primes.miller-rabin
5 math.ranges random sequences sets fry ;
6 IN: math.primes
7
8 <PRIVATE
9
10 : look-in-bitmap ( n -- ? ) >index 4999999 sieve nth ;
11
12 : really-prime? ( n -- ? )
13     dup 5000000 < [ look-in-bitmap ] [ miller-rabin ] if ; foldable
14
15 PRIVATE>
16
17 : prime? ( n -- ? )
18     {
19         { [ dup 2 < ] [ drop f ] }
20         { [ dup even? ] [ 2 = ] }
21         [ really-prime? ]
22     } cond ; foldable
23
24 : next-prime ( n -- p )
25     dup 2 < [
26         drop 2
27     ] [
28         next-odd [ dup really-prime? ] [ 2 + ] until
29     ] if ; foldable
30
31 : primes-between ( low high -- seq )
32     [ dup 3 max dup even? [ 1 + ] when ] dip
33     2 <range> [ prime? ] filter
34     swap 3 < [ 2 prefix ] when ;
35
36 : primes-upto ( n -- seq ) 2 swap primes-between ;
37
38 : coprime? ( a b -- ? ) gcd nip 1 = ; foldable
39
40 : random-prime ( numbits -- p )
41     random-bits* next-prime ;
42
43 : estimated-primes ( m -- n )
44     dup log / ; foldable
45
46 ERROR: no-relative-prime n ;
47
48 <PRIVATE
49
50 : (find-relative-prime) ( n guess -- p )
51     over 1 <= [ over no-relative-prime ] when
52     dup 1 <= [ drop 3 ] when
53     2dup gcd nip 1 > [ 2 + (find-relative-prime) ] [ nip ] if ;
54
55 PRIVATE>
56
57 : find-relative-prime* ( n guess -- p )
58     #! find a prime relative to n with initial guess
59     >odd (find-relative-prime) ;
60
61 : find-relative-prime ( n -- p )
62     dup random find-relative-prime* ;
63
64 ERROR: too-few-primes n numbits ;
65
66 : unique-primes ( n numbits -- seq )
67     2dup 2^ estimated-primes > [ too-few-primes ] when
68     2dup '[ _ random-prime ] replicate
69     dup all-unique? [ 2nip ] [ drop unique-primes ] if ;