]> gitweb.factorcode.org Git - factor.git/blob - basis/math/primes/brute-force/brute-force.factor
Switch to https urls
[factor.git] / basis / math / primes / brute-force / brute-force.factor
1 ! Copyright (C) 2007-2009 Samuel Tardieu.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel make math math.functions math.primes ;
4 IN: math.primes.brute-force
5
6 <PRIVATE
7
8 : count-factor ( n d -- n' c )
9     [ 1 ] 2dip [ /i ] keep
10     [ dupd /mod zero? ] curry [ nip [ 1 + ] dip ] while drop
11     swap ;
12
13 : write-factor ( n d -- n' d' )
14     2dup divisor? [
15         [ [ count-factor ] keep swap 2array , ] keep
16         ! If the remainder is a prime number, increase d so that
17         ! the caller stops looking for factors.
18         over prime? [ drop dup ] when
19     ] when ;
20
21 PRIVATE>
22
23 : brute-force-factors ( n -- seq )
24     [
25         2
26         [ 2dup sq < ] [ write-factor next-prime ] until
27         drop dup 2 < [ drop ] [ 1 2array , ] if
28     ] { } make ;