Slava Pestov 2008-04-16 01:07:33 -05:00
commit c177c76b63
3 changed files with 59 additions and 7 deletions

View File

@ -0,0 +1,53 @@
! Copyright (c) 2008 Eric Mertens
! See http://factorcode.org/license.txt for BSD license.
USING: arrays assocs combinators kernel math sequences math.ranges locals ;
IN: project-euler.076
! http://projecteuler.net/index.php?section=problems&id=76
! DESCRIPTION
! -----------
! How many different ways can one hundred be written as a
! sum of at least two positive integers?
! SOLUTION
! --------
! This solution uses dynamic programming and the following
! recurence relation:
! ways(0,_) = 1
! ways(_,0) = 0
! ways(n,i) = ways(n-i,i) + ways(n,i-1)
<PRIVATE
: init ( n -- table )
[1,b] [ 0 2array 0 ] H{ } map>assoc
1 { 0 0 } pick set-at ;
: use ( n i -- n i )
[ - dup ] keep min ; inline
: ways ( n i table -- )
over zero? [
3drop
] [
[ [ 1- 2array ] dip at ]
[ [ use 2array ] dip at + ]
[ [ 2array ] dip set-at ] 3tri
] if ;
:: each-subproblem ( n quot -- )
n [1,b] [ dup [1,b] quot with each ] each ; inline
PRIVATE>
: (euler076) ( n -- m )
dup init
[ [ ways ] curry each-subproblem ]
[ [ dup 2array ] dip at 1- ] 2bi ;
: euler076 ( -- m )
100 (euler076) ;

View File

@ -30,4 +30,4 @@ IN: project-euler.164
PRIVATE>
: euler164 ( -- n )
init-table 19 [ next-table ] times values sum ;
init-table 19 [ next-table ] times values sum ;

View File

@ -12,17 +12,16 @@ TUPLE: blum-blum-shub x n ;
: generate-bbs-primes ( numbits -- p q )
[ [ random-prime ] curry [ 4 mod 3 = ] generate ] dup bi ;
: next-bbs-bit ( bbs -- bit )
[ [ x>> 2 ] [ n>> ] bi ^mod dup ] keep (>>x) 1 bitand ;
PRIVATE>
: <blum-blum-shub> ( numbits -- blum-blum-shub )
generate-bbs-primes *
[ find-relative-prime ] keep
blum-blum-shub boa ;
: next-bbs-bit ( bbs -- bit )
[ [ x>> 2 ] [ n>> ] bi ^mod ] keep
over >>x drop 1 bitand ;
PRIVATE>
M: blum-blum-shub random-32* ( bbs -- r )
0 32 rot
[ next-bbs-bit swap 1 shift bitor ] curry times ;