Permalink
Browse files

math: adding a fast-gcd that speeds up all ratio operations by up to …

…10 times for bignum ratios.
  • Loading branch information...
1 parent 629677b commit 1b8f1d9945adaaaa039bef3a6f07a8fbfe3cfb3b @mrjbq7 mrjbq7 committed Apr 5, 2012
@@ -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
+
+<PRIVATE
+
+: simple-gcd ( x y -- d ) gcd nip ; inline
+
+PRIVATE>
+
+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
@@ -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
@@ -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*

0 comments on commit 1b8f1d9

Please sign in to comment.