Made p^ more efficient by repeated squaring instead of repeated multiplication

db4
Erik Charlebois 2010-02-13 19:47:44 -08:00
parent 68c5335d50
commit 8f86cc6e51
2 changed files with 8 additions and 6 deletions

View File

@ -17,6 +17,7 @@ IN: math.polynomials.tests
[ { 4 8 0 12 } ] [ 4 { 1 2 0 3 } n*p ] unit-test [ { 4 8 0 12 } ] [ 4 { 1 2 0 3 } n*p ] unit-test
[ { 1 4 4 0 0 } ] [ { 1 2 0 } p-sq ] unit-test [ { 1 4 4 0 0 } ] [ { 1 2 0 } p-sq ] unit-test
[ { 1 6 12 8 0 0 0 } ] [ { 1 2 0 } 3 p^ ] unit-test [ { 1 6 12 8 0 0 0 } ] [ { 1 2 0 } 3 p^ ] unit-test
[ { 1 } ] [ { 1 2 0 } 0 p^ ] unit-test
[ { 1 4 7 6 0 0 0 0 0 } ] [ { 1 2 3 0 0 0 } { 1 2 0 0 } p* ] unit-test [ { 1 4 7 6 0 0 0 0 0 } ] [ { 1 2 3 0 0 0 } { 1 2 0 0 } p* ] unit-test
[ V{ 7 -2 1 } V{ -20 0 0 } ] [ { 1 1 1 1 } { 3 1 } p/mod ] unit-test [ V{ 7 -2 1 } V{ -20 0 0 } ] [ { 1 1 1 1 } { 3 1 } p/mod ] unit-test
[ V{ 0 0 } V{ 1 1 } ] [ { 1 1 } { 1 1 1 1 } p/mod ] unit-test [ V{ 0 0 } V{ 1 1 } ] [ { 1 1 } { 1 1 1 1 } p/mod ] unit-test

View File

@ -1,7 +1,7 @@
! Copyright (C) 2008 Doug Coleman. ! Copyright (C) 2008 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license. ! See http://factorcode.org/license.txt for BSD license.
USING: arrays kernel make math math.order math.vectors sequences USING: arrays kernel make math math.order math.vectors sequences
splitting vectors macros combinators ; splitting vectors macros combinators math.bits ;
IN: math.polynomials IN: math.polynomials
<PRIVATE <PRIVATE
@ -40,12 +40,13 @@ PRIVATE>
ERROR: negative-power-polynomial p n ; ERROR: negative-power-polynomial p n ;
: (p^) ( p n -- p^n )
make-bits { 1 } [ [ over p* ] when [ p-sq ] dip ] reduce nip ;
: p^ ( p n -- p^n ) : p^ ( p n -- p^n )
{ dup 0 >=
{ [ dup 0 > ] [ 1 - dupd [ p* ] with times ] } [ (p^) ]
{ [ dup 0 = ] [ 2drop { 1 } ] } [ negative-power-polynomial ] if ;
{ [ dup 0 < ] [ negative-power-polynomial ] }
} cond ;
<PRIVATE <PRIVATE