1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.vectors sequences ;
4 IN: rosetta-code.long-multiplication
6 ! http://rosettacode.org/wiki/Long_multiplication
8 ! In this task, explicitly implement long multiplication. This
9 ! is one possible approach to arbitrary-precision integer algebra.
11 ! For output, display the result of 2^64 * 2^64. The decimal
12 ! representation of 2^64 is:
14 ! 18446744073709551616
16 ! The output of 2^64 * 2^64 is 2^128, and that is:
18 ! 340282366920938463463374607431768211456
20 : longmult-seq ( xs ys -- zs )
22 dup length iota [ 0 <repetition> ] map
24 [ ] [ [ 0 suffix ] dip v+ ] map-reduce ;
26 : integer->digits ( x -- xs )
27 { } swap [ dup 0 > ] [ 10 /mod swap [ prefix ] dip ] while drop ;
29 : digits->integer ( xs -- x )
30 0 [ swap 10 * + ] reduce ;
32 : longmult ( x y -- z )
33 [ integer->digits ] bi@ longmult-seq digits->integer ;