Use math.algebra to solve project Euler problem 134
parent
c4529fb557
commit
4eb7aad50b
|
@ -1,7 +1,7 @@
|
||||||
! Copyright (c) 2007 Samuel Tardieu.
|
! Copyright (c) 2007 Samuel Tardieu.
|
||||||
! See http://factorcode.org/license.txt for BSD license.
|
! See http://factorcode.org/license.txt for BSD license.
|
||||||
USING: arrays kernel math math.functions math.ranges math.primes.list namespaces
|
USING: arrays kernel math.algebra math math.functions math.primes.list
|
||||||
sequences vars ;
|
math.ranges sequences ;
|
||||||
IN: project-euler.134
|
IN: project-euler.134
|
||||||
|
|
||||||
! http://projecteuler.net/index.php?section=problems&id=134
|
! http://projecteuler.net/index.php?section=problems&id=134
|
||||||
|
@ -23,36 +23,15 @@ IN: project-euler.134
|
||||||
! SOLUTION
|
! SOLUTION
|
||||||
! --------
|
! --------
|
||||||
|
|
||||||
<PRIVATE
|
|
||||||
|
|
||||||
! Compute the smallest power of 10 greater than m
|
! Compute the smallest power of 10 greater than m
|
||||||
: next-power-of-10 ( m -- n )
|
: next-power-of-10 ( m -- n )
|
||||||
10 swap log 10 log / >integer [ 10 * ] times ; foldable
|
10 swap log 10 log / >integer [ 10 * ] times ; foldable
|
||||||
|
|
||||||
! Helper variables and words for the extended Euclidian algorithm
|
! Compute S for a given pair (p1, p2) -- that is the smallest positive
|
||||||
! See http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
|
! number such that X = p1 [npt] and X = 0 [p2] (npt being the smallest
|
||||||
|
! power of 10 above p1)
|
||||||
VARS: r-1 u-1 v-1 r u v ;
|
|
||||||
|
|
||||||
: init ( a b -- )
|
|
||||||
>r >r-1 0 >u 1 >u-1 1 >v 0 >v-1 ;
|
|
||||||
|
|
||||||
: advance ( r u v -- )
|
|
||||||
v> >v-1 >v u> >u-1 >u r> >r-1 >r ;
|
|
||||||
|
|
||||||
: step ( -- )
|
|
||||||
r-1> r> 2dup / >integer [ * - ] keep u-1> over u> * - v-1> rot v> * -
|
|
||||||
advance ;
|
|
||||||
|
|
||||||
! Compute the inverse of a in field Z/bZ where b is prime
|
|
||||||
: inverse ( a b -- a-1 )
|
|
||||||
[ init [ r> 0 > ] [ step ] [ ] while u-1> ] with-scope ;
|
|
||||||
|
|
||||||
! Compute S for a given pair (p1, p2)
|
|
||||||
: s ( p1 p2 -- s )
|
: s ( p1 p2 -- s )
|
||||||
over next-power-of-10 [ over inverse pick * neg swap rem ] keep * + ;
|
over 0 2array rot next-power-of-10 rot 2array chinese-remainder ;
|
||||||
|
|
||||||
PRIVATE>
|
|
||||||
|
|
||||||
: euler134 ( -- answer )
|
: euler134 ( -- answer )
|
||||||
primes-under-million 2 tail dup 1 tail 1000003 add [ s ] 2map sum ;
|
primes-under-million 2 tail dup 1 tail 1000003 add [ s ] 2map sum ;
|
||||||
|
|
Loading…
Reference in New Issue