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 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 mod 0 = ] [ 5 mod 0 = ] } 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
49 : primes-between ( low high -- seq )
50 [ [ 3 max dup even? [ 1 + ] when ] dip 2 <range> ]
51 [ <primes-vector> ] 2bi
52 [ '[ [ prime? ] _ push-if ] each ] keep clone ;
54 : primes-upto ( n -- seq ) 2 swap primes-between ;
56 : coprime? ( a b -- ? ) gcd nip 1 = ; foldable
58 : random-prime ( numbits -- p )
59 [ ] [ 2^ ] [ random-bits* next-prime ] tri
60 2dup < [ 2drop random-prime ] [ 2nip ] if ;
62 : estimated-primes ( m -- n )
65 ERROR: no-relative-prime n ;
69 : (find-relative-prime) ( n guess -- p )
70 over 1 <= [ over no-relative-prime ] when
71 dup 1 <= [ drop 3 ] when
72 2dup gcd nip 1 > [ 2 + (find-relative-prime) ] [ nip ] if ;
76 : find-relative-prime* ( n guess -- p )
77 #! find a prime relative to n with initial guess
78 >odd (find-relative-prime) ;
80 : find-relative-prime ( n -- p )
81 dup random find-relative-prime* ;
83 ERROR: too-few-primes n numbits ;
85 : unique-primes ( n numbits -- seq )
86 2dup 2^ estimated-primes > [ too-few-primes ] when
87 2dup [ random-prime ] curry replicate
88 dup all-unique? [ 2nip ] [ drop unique-primes ] if ;