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 integer>fixnum $[ 8,999,999 sieve ] marked-unsafe? ; inline
15 dup 8,999,999 <= [ look-in-bitmap ] [ miller-rabin ] if ;
18 { [ even? ] [ 3 divisor? ] [ 5 divisor? ] } 1|| ;
24 { [ dup 7 < ] [ { 2 3 5 } member? ] }
25 { [ dup simple? ] [ drop f ] }
29 : next-prime ( n -- p )
33 next-odd [ dup prime? ] [ 2 + ] until
38 : <primes-range> ( low high -- range )
39 [ 3 max dup even? [ 1 + ] when ] dip 2 <range> ;
41 ! In order not to reallocate large vectors, we compute the upper
42 ! bound of the number of primes in a given interval. We use a
43 ! double inequality given by Pierre Dusart in
44 ! http://www.ams.org/mathscinet-getitem?mr=99d:11133 for x >
45 ! 598. Under this limit, we know that there are at most 108
48 dup log [ / ] [ 1.2762 swap / 1 + ] bi * ceiling ;
51 dup log [ / ] [ 0.992 swap / 1 + ] bi * floor ;
53 :: <primes-vector> ( low high -- vector )
54 high upper-pi low lower-pi - >integer
55 108 10000 clamp <vector>
56 low 3 < [ 2 suffix! ] when ;
58 : (primes-between) ( low high -- seq )
59 [ <primes-range> ] [ <primes-vector> ] 2bi
60 [ '[ [ prime? ] _ push-if ] each ] keep ;
64 : primes-between ( low high -- seq )
65 [ ceiling >integer ] [ floor >integer ] bi*
67 { [ 2dup > ] [ 2drop V{ } clone ] }
68 { [ dup 2 = ] [ 2drop V{ 2 } clone ] }
69 { [ dup 2 < ] [ 2drop V{ } clone ] }
73 : primes-upto ( n -- seq )
74 2 swap primes-between ;
76 : nprimes ( n -- seq )
77 2 swap [ [ next-prime ] keep ] replicate nip ;
79 : coprime? ( a b -- ? ) fast-gcd 1 = ; foldable
81 : random-prime ( numbits -- p )
82 [ ] [ 2^ ] [ random-bits* next-prime ] tri
83 2dup < [ 2drop random-prime ] [ 2nip ] if ;
85 : estimated-primes ( m -- n )
88 ERROR: no-relative-prime n ;
90 : find-relative-prime* ( n guess -- p )
91 [ dup 1 <= [ throw-no-relative-prime ] when ]
92 [ >odd dup 1 <= [ drop 3 ] when ] bi*
93 [ 2dup coprime? ] [ 2 + ] until nip ;
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 > [ throw-too-few-primes ] when
102 2dup [ random-prime ] curry replicate
103 dup all-unique? [ 2nip ] [ drop unique-primes ] if ;