1 ! Copyright (C) 2007-2009 Samuel Tardieu.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: combinators combinators.short-circuit fry kernel locals
4 math math.bitwise math.functions math.order math.primes.erato
5 math.primes.erato.private math.primes.miller-rabin math.ranges
6 literals random sequences sets vectors ;
11 : look-in-bitmap ( n -- ? )
12 $[ 8999999 sieve ] marked-unsafe? ; inline
15 dup 8999999 <= [ look-in-bitmap ] [ miller-rabin ] if ;
17 : simple? ( n -- ? ) { [ even? ] [ 3 divisor? ] [ 5 divisor? ] } 1|| ;
23 { [ dup 7 < ] [ { 2 3 5 } member? ] }
24 { [ dup simple? ] [ drop f ] }
28 : next-prime ( n -- p )
32 next-odd [ dup prime? ] [ 2 + ] until
37 : <primes-range> ( low high -- range )
38 [ 3 max dup even? [ 1 + ] when ] dip 2 <range> ;
40 ! In order not to reallocate large vectors, we compute the upper bound
41 ! of the number of primes in a given interval. We use a double inequality given
42 ! by Pierre Dusart in http://www.ams.org/mathscinet-getitem?mr=99d:11133
43 ! for x > 598. Under this limit, we know that there are at most 108 primes.
45 dup log [ / ] [ 1.2762 swap / 1 + ] bi * ceiling ;
48 dup log [ / ] [ 0.992 swap / 1 + ] bi * floor ;
50 :: <primes-vector> ( low high -- vector )
51 high upper-pi low lower-pi - >integer
52 108 10000 clamp <vector>
53 low 3 < [ 2 suffix! ] when ;
55 : (primes-between) ( low high -- seq )
56 [ <primes-range> ] [ <primes-vector> ] 2bi
57 [ '[ [ prime? ] _ push-if ] each ] keep ;
61 : primes-between ( low high -- seq )
62 [ ceiling >integer ] [ floor >integer ] bi*
64 { [ 2dup > ] [ 2drop V{ } clone ] }
65 { [ dup 2 = ] [ 2drop V{ 2 } clone ] }
66 { [ dup 2 < ] [ 2drop V{ } clone ] }
70 : primes-upto ( n -- seq )
71 2 swap primes-between ;
73 : nprimes ( n -- seq )
74 2 swap [ [ next-prime ] keep ] replicate nip ;
76 : coprime? ( a b -- ? ) fast-gcd 1 = ; foldable
78 : random-prime ( numbits -- p )
79 [ ] [ 2^ ] [ random-bits* next-prime ] tri
80 2dup < [ 2drop random-prime ] [ 2nip ] if ;
82 : estimated-primes ( m -- n )
85 ERROR: no-relative-prime n ;
87 : find-relative-prime* ( n guess -- p )
88 [ dup 1 <= [ no-relative-prime ] when ]
89 [ >odd dup 1 <= [ drop 3 ] when ] bi*
90 [ 2dup coprime? ] [ 2 + ] until nip ;
92 : find-relative-prime ( n -- p )
93 dup random find-relative-prime* ;
95 ERROR: too-few-primes n numbits ;
97 : unique-primes ( n numbits -- seq )
98 2dup 2^ estimated-primes > [ too-few-primes ] when
99 2dup [ random-prime ] curry replicate
100 dup all-unique? [ 2nip ] [ drop unique-primes ] if ;