Long multiplication: Difference between revisions
Content added Content deleted
(→{{header|ATS}}: Code simplification and slight commentary revision.) |
(→{{header|Arturo}}: Fixed it with an actual long multiplication program.) |
||
Line 992: | Line 992: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
{{trans|ATS}} |
|||
{{Incorrect|Arturo|Task is "Implement long multiplication" not "Multiply two numbers using native operators"}} |
|||
<syntaxhighlight lang="rebol">print 2^64 * 2</syntaxhighlight> |
|||
The program is written to operate on strings containing digits and spaces. |
|||
<syntaxhighlight lang="arturo"> |
|||
; The following two functions assume the 7-bit encoding is ASCII. |
|||
char2BCD: function [c] [ |
|||
return (and (to :integer c) 15) % 10 |
|||
] |
|||
BCD2char: function [i] [ |
|||
return (to :char (or i 48)) |
|||
] |
|||
multiplyBCD: function [u v] [ |
|||
m: size u |
|||
n: size v |
|||
w: array.of: (m + n) `0` |
|||
predm: m - 1 |
|||
predn: n - 1 |
|||
predszw: (size w) - 1 |
|||
; Long multiplication. See Algorithm 4.3.1M in Volume 2 of Knuth, |
|||
; ‘The Art of Computer Programming’. Here b = 10. Only the less |
|||
; significant nibble of a character is considered. Thus zero can be |
|||
; represented by either `0` or ` `, and other digits by their |
|||
; respective ASCII characters. |
|||
loop 0..predn 'j [ |
|||
vj: char2BCD v\[predn - j] |
|||
if? vj = 0 [ |
|||
set w (predn - j) `0` |
|||
] else [ |
|||
carry: 0 |
|||
loop 0..predm 'i [ |
|||
ui: char2BCD u\[predm - i] |
|||
wij: char2BCD w\[predszw - (i + j)] |
|||
t: (ui * vj) + wij + carry |
|||
[carry digit]: divmod t 10 |
|||
set w (predszw - (i + j)) (BCD2char digit) |
|||
] |
|||
set w (predn - j) (BCD2char carry) |
|||
] |
|||
] |
|||
return join w |
|||
] |
|||
twoRaised64: "18446744073709551616" |
|||
twoRaised128: multiplyBCD twoRaised64 twoRaised64 |
|||
print twoRaised128 |
|||
</syntaxhighlight> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre>0340282366920938463463374607431768211456</pre> |
||
=={{header|ATS}}== |
=={{header|ATS}}== |