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 make math
4 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 -- ? ) $[ 8999999 sieve ] marked-unsafe? ; inline
14 dup 8999999 <= [ look-in-bitmap ] [ miller-rabin ] if ;
16 ! In order not to reallocate large vectors, we compute the upper bound
17 ! of the number of primes in a given interval. We use a double inequality given
18 ! by Pierre Dusart in http://www.ams.org/mathscinet-getitem?mr=99d:11133
19 ! for x > 598. Under this limit, we know that there are at most 108 primes.
21 dup log [ / ] [ 1.2762 swap / 1 + ] bi * ceiling ;
24 dup log [ / ] [ 0.992 swap / 1 + ] bi * floor ;
26 : <primes-vector> ( low high -- vector )
27 swap [ [ upper-pi ] [ lower-pi ] bi* - >integer
28 108 max 10000 min <vector> ] keep
29 3 < [ [ 2 swap push ] keep ] when ;
31 : simple? ( n -- ? ) { [ even? ] [ 3 divisor? ] [ 5 divisor? ] } 1|| ;
37 { [ dup 7 < ] [ { 2 3 5 } member? ] }
38 { [ dup simple? ] [ drop f ] }
42 : next-prime ( n -- p )
46 next-odd [ dup prime? ] [ 2 + ] until
51 : (primes-between) ( low high -- seq )
52 [ [ 3 max dup even? [ 1 + ] when ] dip 2 <range> ]
53 [ <primes-vector> ] 2bi
54 [ '[ [ prime? ] _ push-if ] each ] keep clone ;
58 : primes-between ( low high -- seq )
59 [ ceiling >integer ] [ floor >integer ] bi*
61 { [ 2dup > ] [ 2drop V{ } clone ] }
62 { [ dup 2 = ] [ 2drop V{ 2 } clone ] }
63 { [ dup 2 < ] [ 2drop V{ } clone ] }
67 : primes-upto ( n -- seq ) 2 swap primes-between ;
69 : nprimes ( n -- seq ) [ 2 swap [ dup , next-prime ] times ] { } make nip ;
71 : coprime? ( a b -- ? ) gcd nip 1 = ; foldable
73 : random-prime ( numbits -- p )
74 [ ] [ 2^ ] [ random-bits* next-prime ] tri
75 2dup < [ 2drop random-prime ] [ 2nip ] if ;
77 : estimated-primes ( m -- n )
80 ERROR: no-relative-prime n ;
84 : (find-relative-prime) ( n guess -- p )
85 over 1 <= [ over no-relative-prime ] when
86 dup 1 <= [ drop 3 ] when
87 [ 2dup coprime? ] [ 2 + ] until nip ;
91 : find-relative-prime* ( n guess -- p )
92 #! find a prime relative to n with initial guess
93 >odd (find-relative-prime) ;
95 : find-relative-prime ( n -- p )
96 dup random find-relative-prime* ;
98 ERROR: too-few-primes n numbits ;
100 : unique-primes ( n numbits -- seq )
101 2dup 2^ estimated-primes > [ too-few-primes ] when
102 2dup [ random-prime ] curry replicate
103 dup all-unique? [ 2nip ] [ drop unique-primes ] if ;