From 8f86cc6e51a549697213795b749ba30bd4deab1a Mon Sep 17 00:00:00 2001 From: Erik Charlebois Date: Sat, 13 Feb 2010 19:47:44 -0800 Subject: [PATCH] Made p^ more efficient by repeated squaring instead of repeated multiplication --- basis/math/polynomials/polynomials-tests.factor | 1 + basis/math/polynomials/polynomials.factor | 13 +++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/basis/math/polynomials/polynomials-tests.factor b/basis/math/polynomials/polynomials-tests.factor index e0cedb9adf..08f81a5bfa 100644 --- a/basis/math/polynomials/polynomials-tests.factor +++ b/basis/math/polynomials/polynomials-tests.factor @@ -17,6 +17,7 @@ IN: math.polynomials.tests [ { 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 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 [ 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 diff --git a/basis/math/polynomials/polynomials.factor b/basis/math/polynomials/polynomials.factor index 694b9ef542..b994410283 100644 --- a/basis/math/polynomials/polynomials.factor +++ b/basis/math/polynomials/polynomials.factor @@ -1,7 +1,7 @@ ! Copyright (C) 2008 Doug Coleman. ! See http://factorcode.org/license.txt for BSD license. USING: arrays kernel make math math.order math.vectors sequences - splitting vectors macros combinators ; +splitting vectors macros combinators math.bits ; IN: math.polynomials 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 ) - { - { [ dup 0 > ] [ 1 - dupd [ p* ] with times ] } - { [ dup 0 = ] [ 2drop { 1 } ] } - { [ dup 0 < ] [ negative-power-polynomial ] } - } cond ; + dup 0 >= + [ (p^) ] + [ negative-power-polynomial ] if ;