USING: help.markup help.syntax ;
IN: math.algebra
-HELP: ext-euclidian
-{ $values { "a" "a positive integer" } { "b" "a positive integer" } { "gcd" "a positive integer" } { "u" "an integer" } { "v" "an integer" } }
-{ $description "Compute the greatest common divisor " { $snippet "gcd" } " of integers " { $snippet "a" } " and " { $snippet "b" } " using the extended Euclidian algorithm. In addition, this word also computes two other values " { $snippet "u" } " and " { $snippet "v" } " such that " { $snippet "a*u + b*v = gcd" } "." } ;
-
-HELP: ring-inverse
-{ $values { "a" "a positive integer" } { "b" "a positive integer" } { "i" "a positive integer" } }
-{ $description "If " { $snippet "a" } " and " { $snippet "b" } " are coprime, " { $snippet "i" } " is the smallest positive integer such as " { $snippet "a*i = 1" } " in ring " { $snippet "Z/bZ" } "." } ;
-
HELP: chinese-remainder
{ $values { "aseq" "a sequence of integers" } { "nseq" "a sequence of positive integers" } { "x" "an integer" } }
{ $description "If " { $snippet "nseq" } " integers are pairwise coprimes, " { $snippet "x" } " is the smallest positive integer congruent to each element in " { $snippet "aseq" } " modulo the corresponding element in " { $snippet "nseq" } "." } ;
! Copyright (c) 2007 Samuel Tardieu
! See http://factorcode.org/license.txt for BSD license.
-USING: kernel math math.ranges namespaces sequences vars ;
+USING: kernel math math.functions sequences ;
IN: math.algebra
-<PRIVATE
-
-! The traditional name for the first variable is "r", but we want to avoid
-! a redefinition of "r>" and ">r", so we chose to use "s" instead.
-
-VARS: s-1 u-1 v-1 s u v ;
-
-: init ( a b -- )
- >s >s-1 0 >u 1 >u-1 1 >v 0 >v-1 ;
-
-: advance ( r u v -- )
- v> >v-1 >v u> >u-1 >u s> >s-1 >s ; inline
-
-: step ( -- )
- s-1> s> 2dup /mod drop [ * - ] keep u-1> over u> * - v-1> rot v> * -
- advance ;
-
-PRIVATE>
-
-! Extended Euclidian: http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
-: ext-euclidian ( a b -- gcd u v )
- [ init [ s> 0 > ] [ step ] [ ] while s-1> u-1> v-1> ] with-scope ; foldable
-
-! Inverse a in ring Z/bZ
-: ring-inverse ( a b -- i )
- [ ext-euclidian drop nip ] keep rem ; foldable
-
-! Chinese remainder: http://en.wikipedia.org/wiki/Chinese_remainder_theorem
: chinese-remainder ( aseq nseq -- x )
dup product
- [ [ over / [ ext-euclidian ] keep * 2nip * ] curry 2map sum ] keep rem ;
- foldable
+ [ [ over / [ swap gcd drop ] keep * * ] curry 2map sum ] keep rem ; foldable