From b2ffda32caa270a36f6848c75555afe88ab16194 Mon Sep 17 00:00:00 2001 From: John Benediktsson Date: Thu, 5 Apr 2012 09:17:52 -0700 Subject: [PATCH] math: adding a fast-gcd that speeds up all ratio operations by up to 10 times for bignum ratios. --- basis/math/functions/functions.factor | 14 +++++++++++++- .../math/partial-dispatch/partial-dispatch.factor | 11 +++++++---- basis/math/ratios/ratios.factor | 2 +- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/basis/math/functions/functions.factor b/basis/math/functions/functions.factor index f1e68c9f86..b56e2a4f2c 100644 --- a/basis/math/functions/functions.factor +++ b/basis/math/functions/functions.factor @@ -111,8 +111,20 @@ PRIVATE> : gcd ( x y -- a d ) [ 0 1 ] 2dip (gcd) dup 0 < [ neg ] when ; inline +MATH: fast-gcd ( x y -- d ) foldable + + + +M: real fast-gcd simple-gcd ; inline + +M: bignum fast-gcd bignum-gcd ; inline + : lcm ( a b -- c ) - [ * ] 2keep gcd nip /i ; foldable + [ * ] 2keep fast-gcd /i ; foldable : divisor? ( m n -- ? ) mod 0 = ; inline diff --git a/basis/math/partial-dispatch/partial-dispatch.factor b/basis/math/partial-dispatch/partial-dispatch.factor index fcb789687e..57f2a62309 100644 --- a/basis/math/partial-dispatch/partial-dispatch.factor +++ b/basis/math/partial-dispatch/partial-dispatch.factor @@ -1,9 +1,10 @@ ! Copyright (C) 2008 Slava Pestov. ! See http://factorcode.org/license.txt for BSD license. -USING: accessors kernel kernel.private math math.private words -sequences parser namespaces make assocs quotations arrays -generic generic.math hashtables effects compiler.units -classes.algebra fry combinators ; +USING: accessors kernel kernel.private math math.private +math.functions math.functions.private sequences parser +namespaces make assocs quotations arrays generic generic.math +hashtables effects compiler.units classes.algebra fry +combinators words ; IN: math.partial-dispatch PREDICATE: math-partial < word @@ -215,6 +216,8 @@ SYMBOL: fast-math-ops \ mod \ fixnum-mod \ bignum-mod define-integer-ops \ /i \ fixnum/i \ bignum/i define-integer-ops + \ fast-gcd \ simple-gcd \ bignum-gcd define-integer-ops + \ bitand \ fixnum-bitand \ bignum-bitand define-integer-ops \ bitor \ fixnum-bitor \ bignum-bitor define-integer-ops \ bitxor \ fixnum-bitxor \ bignum-bitxor define-integer-ops diff --git a/basis/math/ratios/ratios.factor b/basis/math/ratios/ratios.factor index dcb8e87e7c..1f95732a18 100644 --- a/basis/math/ratios/ratios.factor +++ b/basis/math/ratios/ratios.factor @@ -30,7 +30,7 @@ M: integer / division-by-zero ] [ dup 0 < [ [ neg ] bi@ ] when - 2dup gcd nip [ /i ] curry bi@ fraction> + 2dup fast-gcd [ /i ] curry bi@ fraction> ] if-zero ; M: ratio hashcode*