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 ;
10 : look-in-bitmap ( n -- ? ) >index 4999999 sieve nth ;
12 : really-prime? ( n -- ? )
13 dup 5000000 < [ look-in-bitmap ] [ miller-rabin ] if ; foldable
19 { [ dup 2 < ] [ drop f ] }
20 { [ dup even? ] [ 2 = ] }
24 : next-prime ( n -- p )
28 next-odd [ dup really-prime? ] [ 2 + ] until
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 ;
36 : primes-upto ( n -- seq ) 2 swap primes-between ;
38 : coprime? ( a b -- ? ) gcd nip 1 = ; foldable
40 : random-prime ( numbits -- p )
41 random-bits* next-prime ;
43 : estimated-primes ( m -- n )
46 ERROR: no-relative-prime n ;
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 ;
57 : find-relative-prime* ( n guess -- p )
58 #! find a prime relative to n with initial guess
59 >odd (find-relative-prime) ;
61 : find-relative-prime ( n -- p )
62 dup random find-relative-prime* ;
64 ERROR: too-few-primes n numbits ;
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 ;