]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/long-multiplication/long-multiplication.factor
core: Rename iota to <iota> so we can have TUPLE: iota ... ; instead of TUPLE: iota...
[factor.git] / extra / rosetta-code / long-multiplication / long-multiplication.factor
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
5
6 ! http://rosettacode.org/wiki/Long_multiplication
7
8 ! In this task, explicitly implement long multiplication. This
9 ! is one possible approach to arbitrary-precision integer algebra.
10
11 ! For output, display the result of 2^64 * 2^64. The decimal
12 ! representation of 2^64 is:
13
14 ! 18446744073709551616
15
16 ! The output of 2^64 * 2^64 is 2^128, and that is:
17
18 ! 340282366920938463463374607431768211456
19
20 : longmult-seq ( xs ys -- zs )
21     [ * ] cartesian-map
22     dup length <iota> [ 0 <repetition> ] map
23     [ prepend ] 2map
24     [ ] [ [ 0 suffix ] dip v+ ] map-reduce ;
25
26 : integer->digits ( x -- xs )
27     { } swap  [ dup 0 > ] [ 10 /mod swap [ prefix ] dip ] while  drop ;
28
29 : digits->integer ( xs -- x )
30     0 [ swap 10 * + ] reduce ;
31
32 : longmult ( x y -- z )
33     [ integer->digits ] bi@ longmult-seq digits->integer ;