! Copyright (C) 2007-2009 Samuel Tardieu. ! See http://factorcode.org/license.txt for BSD license. USING: combinators fry kernel math math.bitwise math.functions math.order math.primes.erato math.primes.erato.private math.primes.miller-rabin math.ranges literals random sequences sets vectors ; IN: math.primes 598. Under this limit, we know that there are at most 108 primes. : upper-pi ( x -- y ) dup log [ / ] [ 1.2762 swap / 1 + ] bi * ceiling ; : lower-pi ( x -- y ) dup log [ / ] [ 0.992 swap / 1 + ] bi * floor ; : ( low high -- vector ) swap [ [ upper-pi ] [ lower-pi ] bi* - >integer 108 max 10000 min ] keep 3 < [ [ 2 swap push ] keep ] when ; PRIVATE> : prime? ( n -- ? ) { { [ dup 7 < ] [ { 2 3 5 } member? ] } { [ dup even? ] [ 2 = ] } [ (prime?) ] } cond ; foldable : next-prime ( n -- p ) dup 2 < [ drop 2 ] [ next-odd [ dup prime? ] [ 2 + ] until ] if ; foldable : primes-between ( low high -- seq ) [ [ 3 max dup even? [ 1 + ] when ] dip 2 ] [ ] 2bi [ '[ [ prime? ] _ push-if ] each ] keep clone ; : primes-upto ( n -- seq ) 2 swap primes-between ; : coprime? ( a b -- ? ) gcd nip 1 = ; foldable : random-prime ( numbits -- p ) random-bits* next-prime ; : estimated-primes ( m -- n ) dup log / ; foldable ERROR: no-relative-prime n ; [ 2 + (find-relative-prime) ] [ nip ] if ; PRIVATE> : find-relative-prime* ( n guess -- p ) #! find a prime relative to n with initial guess >odd (find-relative-prime) ; : find-relative-prime ( n -- p ) dup random find-relative-prime* ; ERROR: too-few-primes n numbits ; : unique-primes ( n numbits -- seq ) 2dup 2^ estimated-primes > [ too-few-primes ] when 2dup [ random-prime ] curry replicate dup all-unique? [ 2nip ] [ drop unique-primes ] if ;