Long multiplication: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|PL/I}}: Added syntax highlighting) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 23:
{{trans|Python}}
<
L
L result.len < addendpos + 1
Line 53:
V sixtyfour = ‘18446744073709551616’
print(longhand_multiplication(sixtyfour, sixtyfour))</
{{out}}
Line 62:
=={{header|360 Assembly}}==
For maximum compatibility, we use only the basic 370 instruction set (use of MVCL). Pseudo-macro instruction XPRNT can be replaced by a WTO.
<
USING LONGINT,R13
SAVEAREA B PROLOG-SAVEAREA(R15)
Line 334:
LL EQU 94
YREGS
END LONGINT</
{{out}}
<pre>
Line 348:
First we specify the required operations and declare our number type as an array of digits (in base 2^16):
<
type Number (<>) is private;
Line 381:
Result : out Number;
Remainder : out Digit);
end Long_Multiplication;</
Some of the operations declared above are useful helper operations for the conversion of numbers to and from base 10 digit strings.
Then we implement the operations:
<
function Value (Item : in String) return Number is
subtype Base_Ten_Digit is Digit range 0 .. 9;
Line 529:
return Zero;
end Trim;
end Long_Multiplication;</
And finally we have the requested test application:
<
with Long_Multiplication;
Line 542:
begin
Put_Line (Image (N) & " * " & Image (N) & " = " & Image (M));
end Test_Long_Multiplication;</
{{out}}
Line 550:
The following implementation uses representation of a long number by an array of 32-bit elements:
<
function "*" (Left, Right : Long_Number) return Long_Number is
Line 573:
end loop;
return (0 => 0);
end "*";</
The task requires conversion into decimal base. For this we also need division to short number with a remainder. Here it is:
<
( Dividend : in out Long_Number;
Last : in out Natural;
Line 596:
Remainder := Unsigned_32 (Accum);
Last := Size;
end Div;</
With the above the test program:
<
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
Line 624:
begin
Put (X);
end Long_Multiplication;</
Sample output:
Line 632:
=={{header|Aime}}==
<
integer d, e, i, j, s;
Line 670:
}
o_form("~\n", c);</
=={{header|ALGOL 68}}==
Line 680:
[[ALGOL 68G]] allows any precision for '''long long int''' to be defined
when the program is run, e.g. 200 digits.
<
MODE INTEGER = LONG LONG INT;
Line 700:
INTEGER neg two to the power of 64 = -(LONG 2 ** 64);
print(("2 ** 64 * -(2 ** 64) = ", whole(two to the power of 64*neg two to the power of 64,width), new line))
)</
Output:
<pre>
Line 713:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
<!-- {{does not works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - translator throws and assert. I'm not sure why.}} -->
<
MODE INTEGER = FLEX[0]DIGIT; # an arbitary number of digits #
Line 805:
# finally return the semi-normalised result #
IF leading zeros = UPB out THEN "0" ELSE sign + out[leading zeros+1:] FI
);</
<
# Finally Define the required INTEGER multiplication OPerator. #
################################################################
Line 829:
OD;
NORMALISE ab
);</
<
OP - = (INTEGER a)INTEGER: raise integer not implemented error("monadic minus"),
ABS = (INTEGER a)INTEGER: raise integer not implemented error("ABS"),
Line 860:
INTEGER neg two to the power of 64 = INTEGERINIT(-(LONG 2 ** 64));
print(("2 ** 64 * -(2 ** 64) = ", REPR (two to the power of 64 * neg two to the power of 64), new line))
)</
Output:
Line 874:
=={{header|ALGOL W}}==
<
% long multiplication of large integers %
% large integers are represented by arrays of integers whose absolute %
Line 985:
writeonLargeInteger( twoTo128, ELEMENT_COUNT )
end
end.</
{{out}}
<pre>
Line 993:
=={{header|Arturo}}==
<syntaxhighlight lang
{{out}}
Line 1,001:
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=149 discussion]
<
MsgBox % x := mul(x,x)
MsgBox % x := mul(x,x) ; 18446744073709551616
Line 1,019:
}
Return cy ? a : SubStr(a,2)
}</
=={{header|AWK}}==
Line 1,025:
{{works with|nawk|20100523}}
{{trans|Tcl}}
<
DEBUG = 0
n = 2^64
Line 1,112:
print "===="
}
}</
outputs:
<pre>2^64 * 2^64 = 340282366920938463463374607431768211456
Line 1,121:
===Version 1===
<
'LRCVS 01.01.2010
'THIS PROGRAM SIMPLY MAKES A MULTIPLICATION
Line 1,267:
CLS
PRINT "THE SOLUTION IN THE FILE: R"
END SUB</
===Version 2===
<!-- I'm not sure what the difference is; don't feel like reading through them, I was just making sure they work and bughunting. -->
<
'LRCVS 01/01/2010
'THIS PROGRAM SIMPLY MAKES A BIG MULTIPLICATION
Line 1,377:
NEXT N
PRINT "END"
PRINT "THE SOLUTION IN THE FILE: R.MLT"</
==={{header|Applesoft BASIC}}===
<
110 B$ = A$
120 GOSUB 400
Line 1,412:
680 NEXT J
700 IF E THEN V = VAL ( MID$ (D$,E,1)) + C:C = V > 9:V = V - 10 * C:E$ = STR$ (V) + E$:E = E - 1: GOTO 700
720 RETURN</
=={{header|Batch File}}==
Based on the JavaScript iterative code.
<
::Batch File Implementation
Line 1,473:
for /l %%F in (0,1,%length%) do set "prod=!digit%%F!!prod!"
endlocal & set "%3=%prod%"
goto :eof</
{{Out}}
<pre>340282366920938463463374607431768211456</pre>
Line 1,480:
{{works with|BBC BASIC for Windows}}
Library method:
<
MAPM_DllPath$ = @lib$+"BB4WMAPM.DLL"
PROCMAPM_Init
twoto64$ = "18446744073709551616"
PRINT "2^64 * 2^64 = " ; FNMAPM_Multiply(twoto64$, twoto64$)</
Explicit method:
<
PRINT "2^64 * 2^64 = " ; FNlongmult(twoto64$, twoto64$)
END
Line 1,514:
num3&(S%) = 0
IF num3&(0) = &30 THEN = $$^num3&(1)
= $$^num3&(0)</
=={{header|C}}==
Doing it as if by hand.
<
#include <string.h>
Line 1,572:
return 0;
}</
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|4+}}If you strip out the ''BigInteger'' checking, it will work with lesser versions.<br/><br/>This uses the '''decimal''' type, (which has a '''MaxValue''' of 79,228,162,514,264,337,593,543,950,335). By limiting it to '''10^28''', it allows 28 decimal digits for the ''hi'' part, and 28 decimal digits for the ''lo'' part, '''56 decimal digits''' total. A side computation of ''BigInteger'' assures that the results are accurate.
<
using static System.Console;
using BI = System.Numerics.BigInteger;
Line 1,615:
BS.ToString() == toStr(y) ? "does" : "fails to"); } }
}</
{{out}}
<pre>The square of (2^64): 18,446,744,073,709,551,616
Line 1,625:
=={{header|C++}}==
===Version 1===
<
#include <iostream>
#include <sstream>
Line 1,706:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
{{out}}
<pre>340282366920938463463374607431768211456
Line 1,717:
===Version 2===
<
#include <iostream>
#include <vector>
Line 1,784:
}
return 0;
}</
<pre>
Line 1,797:
=={{header|Ceylon}}==
<
shared void run() {
Line 1,854:
print("The actual result is ``result``");
print("Do they match? ``expectedResult == result then "Yes!" else "No!"``");
}</
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
identification division.
program-id. long-mul.
Line 1,946:
end program long-mul.
</syntaxhighlight>
<pre>
Line 1,955:
=={{header|CoffeeScript}}==
<
# This very limited BCD-based collection of functions
# allows for long multiplication. It works for positive
Line 2,020:
square = BcdInteger.product x, x
console.log BcdInteger.to_string square # 340282366920938463463374607431768211456
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(do ((digits '())) ((zerop number) digits)
(multiple-value-bind (quotient remainder) (floor number 10)
Line 2,062:
(let* ((bi (pop b))
(row (mapcar #'(lambda (ai) (* ai bi)) a)))
(push (append prefix row) rows)))))</
> (long-multiply (expt 2 64) (expt 2 64))
Line 2,069:
=={{header|Crystal}}==
<
a = 2.to_big_i ** 64
puts "#{a} * #{a} = #{a*a}"
</syntaxhighlight>
{{out}}
<pre>
Line 2,081:
=={{header|D}}==
Using the standard library:
<
import std.stdio, std.bigint;
writeln(2.BigInt ^^ 64 * 2.BigInt ^^ 64);
}</
{{out}}
<pre>340282366920938463463374607431768211456</pre>
Long multiplication, same output:
{{trans|JavaScript}}
<
auto longMult(in string x1, in string x2) pure nothrow @safe {
Line 2,120:
immutable two64 = "18446744073709551616";
longMult(two64, two64).writeln;
}</
=={{header|Dc}}==
{{incorrect|Dc|Code does not explicitly implement long multiplication}}
Since Dc has arbitrary precision built-in, the task is no different than a normal multiplication:
<
{{incorrect|Dc|A Dc solution might be: Represent bignums as numerical strings and implement arithmetic functions on them.}}
=={{header|Delphi}}==
Line 2,131:
{{Trans|Go}}
Copy of core Go answer.
<syntaxhighlight lang="delphi">
program Long_multiplication;
Line 2,282:
Writeln(validate);
Readln;
end.</
{{out}}
<pre>340282366920938463463374607431768211456
Line 2,289:
=={{header|EchoLisp}}==
We implement long multiplication by multiplying polynomials, knowing that the number 1234 is the polynomial x^3 +2x^2 +3x +4 at x=10. As we assume no bigint library is present, long-mul operates on strings.
<
(lib 'math) ;; for poly multiplication
Line 2,331:
</syntaxhighlight>
=={{header|Euphoria}}==
<
function atom_to_long(atom a)
Line 2,391:
c = long_mult(b,b)
printf(1,"a*a*a*a is %s\n",{long_to_str(c)})</
Output:
Line 2,402:
{{incorrect|F#|The problem is to implement long multiplication, not to demonstrate bignum support.}}
<
val X : System.Numerics.BigInteger = 340282366920938463463374607431768211456
</syntaxhighlight>
=={{header|Factor}}==
<
: longmult-seq ( xs ys -- zs )
Line 2,419:
: digits->integer ( xs -- x ) 0 [ swap 10 * + ] reduce ;
: longmult ( x y -- z ) [ integer->digits ] bi@ longmult-seq digits->integer ;</
<
340282366920938463463374607431768211456
( scratchpad ) 2 64 ^ dup * .
340282366920938463463374607431768211456</
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 2,501:
end subroutine longmolt_print
end module LongMoltiplication</
<
use LongMoltiplication
Line 2,515:
write(*,*)
end program Test</
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 2,612:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>2 ^ 2 = 4
Line 2,627:
=={{header|Go}}==
<
// That is, multiplicand is multiplied by single digits of multiplier
// to form intermediate results. Intermediate results are accumulated
Line 2,705:
func main() {
fmt.Println(mul(n, n))
}</
Output:
<pre>
Line 2,712:
=={{header|Haskell}}==
<
import Data.Char (digitToInt)
Line 2,731:
main :: IO ()
main = print $ (2 ^ 64) `longmult` (2 ^ 64)</
{{out}}
<pre>340282366920938463463374607431768211456</pre>
Line 2,737:
=={{header|Icon}} and {{header|Unicon}}==
Large integers are native to Icon and Unicon. Neither libraries nor special programming is required.
<
write(2^64*2^64)
end</
{{output}}<pre>340282366920938463463374607431768211456</pre>
=={{header|J}}==
'''Solution:'''
<
polymult =: +//.@(*/)
buildDecimal=: 10x&#.
longmult=: buildDecimal@polymult&digits</
'''Example:'''
<
340282366920938463463374607431768211456</
'''Alternatives:'''<br>
<code>longmult</code> could have been defined concisely:
<
Or, of course, the task may be accomplished without the verb definitions:
<
340282366920938463463374607431768211456</
Or using the code <code>(+ 10x&*)/@|.</code> instead of <code>#.</code>:
<
340282366920938463463374607431768211456</
Or you could use the built-in language support for arbitrary precision multiplication:
<
340282366920938463463374607431768211456</
'''Explaining the component verbs:'''
* <code>digits</code> translates a number to a corresponding list of digits;
<
1 2 3</
* <code>polymult</code> (multiplies polynomials): '''ref.''' [http://www.jsoftware.com/help/dictionary/samp23.htm]
<
1 4 10 12 9</
* <code>buildDecimal</code> (translates a list of decimal digits - possibly including "carry" - to the corresponding extended precision number):
<
15129</
=={{header|Java}}==
Line 2,783:
This version of the code keeps the data in base ten. By doing this, we can avoid converting the whole number to binary and we can keep things simple, but the runtime will be suboptimal.
<
private static byte[] stringToDigits(String num) {
Line 2,834:
}
}
</syntaxhighlight>
===Binary version===
Line 2,840:
This version tries to be as efficient as possible, so it converts numbers into binary before doing any calculations. The complexity is higher because of the need to convert to and from base ten, which requires the implementation of some additional arithmetic operations beyond long multiplication itself.
<
public class LongMultBinary {
Line 3,045:
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 3,059:
This means that to handle larger inputs, the multiplication function needs to have string parameters:
<
var a1 = strNum1.split("").reverse();
Line 3,080:
mult('18446744073709551616', '18446744073709551616')</
{{Out}}
Line 3,091:
For the same reason, the output always takes the form of an arbitrary precision integer string, rather than a native integer data type. (See the '''largeIntegerString()''' helper function below)
<
'use strict';
Line 3,180:
)
};
})();</
{{Out}}
<pre>{"fromIntegerStrings":"340282366920938463463374607431768211456",
Line 3,188:
{{Works with|jq|1.4}}
Since the task description mentions 2^64, the following includes "long_power(i)" for computing n^i.
<
def long_multiply(num1; num2):
Line 3,233:
elif $a2[1] == "1" then $a1[1]|adjustsign( $a1[0] * $a2[0] )
else mult($a1[1]; $a2[1]) | adjustsign( $a1[0] * $a2[0] )
end;</
<
# represented as numbers and/or strings.
def long_power(i):
Line 3,251:
| ($i - $j*$j) as $k
| long_multiply( power($j) | power($j) ; power($k) )
end ;</
'''Example''':
<
{{Out}}
$ jq -n -f Long_multiplication.jq
Line 3,263:
'''Module''':
<
using Compat
Line 3,307:
end
end # module LongMultiplication</
'''Main''':
<
@show LongMultiplication.longmult("18446744073709551616", "18446744073709551616")</
{{out}}
Line 3,319:
=={{header|Kotlin}}==
{{trans|Java}}
<
if (!c.isDigit())
throw IllegalArgumentException("Invalid digit $c found at position $i")
Line 3,354:
fun main(args: Array<out String>) {
println("18446744073709551616" * "18446744073709551616")
}</
=={{header|Lambdatalk}}==
<
Natural positive numbers are defined as strings, for instance 123 -> "123".
{lambda talk} has a small set of primitives working on strings, [equal?, empty?, chars, charAt, substring]
Line 3,436:
This can be tested in http://lambdaway.free.fr/lambdaspeech/?view=numbers8
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
'[RC] long multiplication
Line 3,531:
</syntaxhighlight>
=={{header|Lobster}}==
{{trans|Java}} Translation of Java binary version, but with base 1000000000
<
// Very basic arbitrary-precision integers
Line 3,648:
var pro = one.bign_multiply(two)
print(bign2str(pro))
</syntaxhighlight>
{{out}}
<pre>
Line 3,655:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
longmult := proc(a::integer,b::integer)
local A,B,m,n,i,j;
Line 3,668:
> longmult( 2^64, 2^64 );
340282366920938463463374607431768211456
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
We define the long multiplication function:
<
d1=IntegerDigits[a]//Reverse;
d2=IntegerDigits[b]//Reverse;
Sum[d1[[i]]d2[[j]]*10^(i+j-2),{i,1,Length[d1]},{j,1,Length[d2]}]
]</
Example:
<
n2 = 2^64;
LongMultiplication[n1, n2]</
gives back:
<syntaxhighlight lang
To check the speed difference between built-in multiplication (which is already arbitrary precision) we multiply two big numbers (2^8000 has '''2409''' digits!) and divide their timings:
<
n2=2^8000;
Timing[LongMultiplication[n1,n2]][[1]]
Timing[n1 n2][[1]]
Floor[%%/%]</
gives back:
<
7.*10^-6
10424088</
So our custom function takes about 73 second, the built-in function a couple of millionths of a second, so the long multiplication is about 10.5 million times slower! Mathematica uses Karatsuba multiplication for large integers, which is several magnitudes faster for really big numbers. Making it able to multiply <math>3^{(10^7)}\times3^{(10^7)}</math> in about a second; the final result has 9542426 digits; result omitted for obvious reasons.
Line 3,703:
{{trans|REXX}}
A reworking of the example at Rexx Version 2.
<
options replace format comments java crossref symbols nobinary
Line 3,784:
return
</syntaxhighlight>
{{out}}
<pre>
Line 3,814:
{{trans|C}}
<
proc ti(a: char): int = ord(a) - ord('0')
Line 3,854:
result[0..result.high-1] = result[1..result.high]
echo longmulti("-18446744073709551616", "-18446744073709551616")</
Output:
<pre>3402823669209384634633746074317682114566</pre>
Line 3,876:
Just multiplication is implemented here.
<
Natural method: initialize := v ;
Line 3,903:
| i |
@v last <<
@v size 1 - loop: i [ @v at(@v size i -) <<wjp(0, JUSTIFY_RIGHT, 8) ] ;</
{{out}}
Line 3,927:
Ol already supports long numbers "out-of-the-box".
<
(define x (* 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2)) ; 2^64
(print (* x x))
</syntaxhighlight>
<pre>
340282366920938463463374607431768211456
Line 3,937:
=={{header|PARI/GP}}==
<
a=eval(Vec(a));
b=eval(Vec(b));
Line 3,956:
"0"
};
long("18446744073709551616","18446744073709551616")</
Output:
<pre>%1 = "340282366920938463463374607431768211456"</pre>
Line 3,962:
=={{header|Pascal}}==
Extracted from a programme to calculate and factor the number (two versions) in Frederick Pohl's book ''The Gold at the Starbow's End'', and compute Godel encodings of text. Compiles with the Free Pascal Compiler. The original would compile with Turbo Pascal (and used pointers to allow access to the "heap" storage scheme) except that does not allow functions to return a "big number" data aggregate, and it is so much nicer to be able to write X:=BigMult(A,B); The original has a special "square" calculation but this task is to exhibit long multiplication. However, raising to a power by iteration is painful, so a special routine for that.
<syntaxhighlight lang="pascal">
Program TwoUp; Uses DOS, crt;
{Concocted by R.N.McLean (whom God preserve), Victoria university, NZ.}
Line 4,100:
Write ('x*x = ');BigShow(X); {Can't have Write('x*x = ',BigShow(BigMult(X,X))), after all. Oh well.}
END.
</syntaxhighlight>
Output:
Line 4,108:
=={{header|Perl}}==
<
use strict;
Line 4,162:
my $onetwentyeight = &longhand_multiplication($sixtyfour, $sixtyfour);
print "$onetwentyeight\n";</
=={{header|Phix}}==
Line 4,170:
If bcd1 is a number split into digits 0..9, bcd9 is a number split into "digits" 000,000,000..999,999,999, which fit in an integer.<br>
They are held lsb-style mainly so that trimming a trailing 0 does not alter their value.
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">base</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1_000_000_000</span>
Line 4,223:
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bcd9_mult</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"a*a*a*a is %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">bcd9_to_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)})</span>
<!--</
{{out}}
<pre>
Line 4,232:
=== string ===
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">mul</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">)</span>
Line 4,261:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">mul</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"18446744073709551616"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"18446744073709551616"</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 4,270:
{{libheader|Phix/mpfr}}
(same output as immediately above)
<!--<
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"18446744073709551616"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- or:
Line 4,276:
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<!--</
=={{header|PHP}}==
<
function longMult($a, $b)
{
Line 4,347:
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">
(de multi (A B)
(setq A (format A) B (reverse (chop B)))
Line 4,353:
(for (I . X) B
(setq Result (+ Result (* (format X) A (** 10 (dec I)))))) ) )
</syntaxhighlight>
=={{header|PL/I}}==
<
multiply: procedure (a, b, c);
declare (a, b, c) (*) fixed decimal (1);
Line 4,402:
a(i) = s;
end;
end complement;</
Calling sequence:
<
a(60) = 1;
do i = 1 to 64; /* Generate 2**64 */
Line 4,414:
call multiply (a, b, c);
put skip;
call output (c);</
Final output:
<pre>
Line 4,423:
=={{header|PL/M}}==
Based on the Algol W sample, Uses bytes instead of integers to hold the digits. Ony handles positive numbers.
<
/* LARGE INTEGERS ARE REPRESENTED BY ARRAYS OF BYTES WHOSE VALUES ARE */
/* A SINGLE DECIMAL DIGIT OF THE NUMBER */
Line 4,518:
CALL PRINT$LONG$INTEGER( .TWO$TO$128 );
CALL PRINT$NL;
EOF</
{{out}}
<pre>
Line 4,526:
=={{header|PowerShell}}==
===Implementation===
<syntaxhighlight lang="powershell">
# LongAddition only supports Unsigned Integers represented as Strings/Character Arrays
Function LongAddition ( [Char[]] $lhs, [Char[]] $rhs )
Line 4,606:
}
LongMultiplication "18446744073709551616" "18446744073709551616"</
===Library Method===
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
[BigInt]$n = [Math]::Pow(2,64)
[BigInt]::Multiply($n,$n)
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 4,620:
=={{header|Prolog}}==
Arbitrary precision arithmetic is native in most Prolog implementations.
<
X = 340282366920938463463374607431768211456.</
=={{header|PureBasic}}==
===Explicit Implementation===
<
Array Digit.b(0) ;contains each digit of number, right-most digit is index 0
digitCount.i ;zero based
Line 4,813:
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Output:
<pre>The result of 2^64 * 2^64 is 340282366920938463463374607431768211456</pre>
Line 4,821:
Using [http://www.purebasic.fr/english/viewtopic.php?p=309763#p309763 Decimal.pbi] by Stargåte allows for calculation with long numbers, this is useful since version 4.41 of PureBasic mostly only supporter data types native to x86/x64/PPC etc processors.
<
Define.Decimal *a, *b
Line 4,827:
*b=TimesDecimal(*a,*a,#NoDecimal)
Print("2^64*2^64 = "+DecimalToString(*b))</
'''Outputs
Line 4,835:
(Note that Python comes with arbitrary length integers).
<
print 2**64*2**64</
{{works with|Python|3.0}}
{{trans|Perl}}
<
def add_with_carry(result, addend, addendpos):
Line 4,872:
onetwentyeight = longhand_multiplication(sixtyfour, sixtyfour)
print(onetwentyeight)</
Shorter version:
{{trans|Haskell}}
{{Works with|Python|3.7}}
<
from functools import reduce
Line 4,919:
print(
longmult(2 ** 64, 2 ** 64)
)</
Line 4,930:
In addition to the specified task, we were always encouraged to show our workings.
<
[ [] swap witheach
Line 5,066:
cr cr
say "(Show your workings.)" cr cr
2 64 ** long dup workings cr</
{{out}}
Line 5,107:
===Using GMP===
{{libheader|gmp}}
<
a <- as.bigz("18446744073709551616")
mul.bigz(a,a)</
"340282366920938463463374607431768211456"
===A native implementation===
This code is more verbose than necessary, for ease of understanding.
<
{
#get the number described in each string
Line 5,178:
a <- "18446744073709551616"
longmult(a, a)</
<pre>
"340282366920938463463374607431768211456"
Line 5,184:
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 5,221:
;; 340282366920938463463374607431768211456
;; 340282366920938463463374607431768211456
</syntaxhighlight>
=={{header|Raku}}==
Line 5,227:
{{works with|rakudo|2015-09-17}}
For efficiency (and novelty), this program explicitly implements long multiplication, but in base 10000. That base was chosen because multiplying two 5-digit numbers can overflow a 32-bit integer, but two 4-digit numbers cannot.
<syntaxhighlight lang="raku"
sub groups_to_num ( @g ) { [~] flat @g.pop, @g.reverse».fmt('%04d') };
Line 5,249:
# cross-check with native implementation
say +$str * +$str;</
{{out}}
Line 5,265:
Programming note: <big>&&</big> is REXX's '''exclusive or''' operand.
<
numeric digits 300 /*be able to handle gihugeic input #s. */
parse arg x y . /*obtain optional arguments from the CL*/
Line 5,289:
if f<0 then $=copies(0, abs(f) + 1)$ /*Negative? Add leading 0s for INSERT.*/
say 'long mult:' xx "*" yy '──►' sign || strip( insert(., $, length($) - #), 'T', .)
say ' built─in:' xx "*" yy '──►' xx*yy /*stick a fork in it, we're all done. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 5,307:
===version 2===
<
* While REXX can multiply arbitrary large integers
* here is the algorithm asked for by the task description
Line 5,385:
ol=ol||value(name'.z')
End
Return ol</
Output:
<pre>soll = 15129
Line 5,402:
=={{header|Ring}}==
{{Incorrect|Ring|Task is "Implement long multiplication" not "Multiply two numbers using native operators"}}
<
decimals(0)
see pow(2,64)*pow(2,64) + nl
</syntaxhighlight>
Output:
<pre>
Line 5,413:
=={{header|Ruby}}==
{{trans|Tcl}}
<
result = [0]
j = 0
Line 5,435:
n=2**64
printf " %d * %d = %d\n", n, n, n*n
printf "longmult(%d, %d) = %d\n", n, n, longmult(n,n)</
<pre> 18446744073709551616 * 18446744073709551616 = 340282366920938463463374607431768211456
longmult(18446744073709551616, 18446744073709551616) = 340282366920938463463374607431768211456</pre>
Line 5,443:
are ever multiplied or added, and all partial results are kept as string.
<
val padSize = x.length max y.length
val paddedX = "0" * (padSize - x.length) + x
Line 5,465:
def mult(x: String, y: String) =
y.foldLeft("")((acc, digit) => addNums(acc + "0", multByDigit(x, digit.asDigit)))</
Sample:
Line 5,477:
Scala 2.8 introduces `scanLeft` and `scanRight` which can be used to simplify this further:
<
result
.map(_ % 10) // remove carry from each digit
Line 5,499:
def mult(x: String, y: String) =
y.foldLeft("")((acc, digit) => addNums(acc + "0", multByDigit(x, digit.asDigit)))
</syntaxhighlight>
=={{header|Scheme}}==
Since Scheme already supports arbitrary precision arithmetic, build it out of church numerals. Don't try converting these to native integers. You will die waiting for the answer.
<
(define (add a b) (lambda (f) (lambda (x) ((a f) ((b f) x)))))
(define (mult a b) (lambda (f) (lambda (x) ((a (b f)) x))))
Line 5,511:
(define six (add two (add two two)))
(define sixty-four (expo two six))
(display (mult (expo two sixty-four) (expo two sixty-four)))</
{{out}}
<small>(as run on Chicken Scheme on tio)</small>
Line 5,526:
[http://seed7.sourceforge.net/libraries/bigint.htm#%28in_bigInteger%29*%28in_bigInteger%29 *]:
<
include "bigint.s7i";
Line 5,532:
begin
writeln(2_**64 * 2_**64);
end func;</
Output:
Line 5,546:
The multiplication example below uses the requested inferior implementation:
<
const func string: (in string: a) * (in string: b) is func
Line 5,587:
begin
writeln("-18446744073709551616" * "-18446744073709551616");
end func;</
The output is the same as with the superior solution.
Line 5,593:
=={{header|Sidef}}==
(Note that arbitrary precision arithmetic is native in Sidef).
<
{{trans|Python}}
<
loop {
while (result.len < addendpos+1) {
Line 5,631:
}
say longhand_multiplication('18446744073709551616', '18446744073709551616')</
{{out}}
Line 5,639:
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
Note that arbitrary precision arithmetic is native in Smalltalk, and no-one would reinvent the wheel.
<
or, to display it:
<
"if ** is defined as alias: " Transcript showCR:(2 ** 64) * (2 ** 64).</
{{out}}
340282366920938463463374607431768211456
Line 5,658:
(not that I know of any Smalltalk ever ported to a Zuse 1 :-)
<
"/ as the language does not specify, how many bits are used to represent
"/ SmallIntegers, and when the VM uses LargeInts.
Line 5,795:
"/ verify...
printedString := String streamContents:[:s | printOn value:rslt value:s].
self assert:(printedString = (2**64) squared printString)</
{{out}}
3402823669293846346337467431768211456
Line 5,801:
The above code does not really integrate into the Smalltalk class library. For example, it will not allow mixed mode arithmetic between regular integers and ''Rosetta integers''.
Here is a full example in portable chunk file format which makes mixed mode arithmetic completely transparent (I implemented only addition and multiplication):
<
subclass: #RosettaInteger
instanceVariableNames:'digitArray'
Line 6,011:
Transcript show:'once again: '.
result := (2 asRosettaInteger raisedTo:64) squared.
Transcript showCR:result.</
{{out}}
<pre>a is: 124 (RosettaInteger)
Line 6,027:
{{works with|Tcl|8.5}}
Tcl 8.5 supports arbitrary-precision integers, which improves math operations on large integers. It is easy to define our own by following rules for long multiplication; we can then check this against the built-in's result:
<
proc longmult {x y} {
Line 6,054:
puts [set n [expr {2**64}]]
puts [longmult $n $n]
puts [expr {$n * $n}]</
outputs
<pre>18446744073709551616
Line 6,064:
In real shell scripts, I would use either `bc` or `dc` for this:
<
But you can also do it with bash's built-in arithmetic:
<
local a="$1" b="$2" sum= carry=0
if (( ${#a} < ${#b} )); then
Line 6,110:
done
echo "$product"
}</
Output is the same either way:<pre>$ multiply 18446744073709551616 18446744073709551616
Line 6,126:
them in decimal.
<
sum = ~&B^?a\~&Y@a ~&B?abh/successor@alh2fabt2RC ~&Yabh2Ofabt2RC
Line 6,136:
#show+
y = %nP product@iiX x</
output:
<pre>340282366920938463463374607431768211456</pre>
Line 6,142:
=={{header|Vedit macro language}}==
This example multiplies the value on current line with the value on next line and stores result on the 3rd line.
<
#11 = EOL_Pos-Cur_Pos
#12 = EOL_Pos-1
Line 6,166:
}
}
} </
Sample input and output:
<pre>
Line 6,177:
{{trans|C#}}<br/>
This uses the '''decimal''' type, (which has a '''MaxValue''' of 79,228,162,514,264,337,593,543,950,335). By limiting it to '''10^28''', it allows 28 decimal digits for the ''hi'' part, and 28 decimal digits for the ''lo'' part, '''56 decimal digits''' total. A side computation of ''BigInteger'' assures that the results are accurate.
<
Imports System.Console
Imports BI = System.Numerics.BigInteger
Line 6,223:
End Sub
End Module</
{{out}}Shown are the prescribed output and the maximum power of two that can be squared by this '''''bd''''' structure without overflowing.
<pre>The square of (2^64): 18,446,744,073,709,551,616
Line 6,234:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
// argument validation
Line 6,297:
var n = "18446744073709551616"
Fmt.print("$,s", mul.call(n, n))</
{{out}}
Line 6,305:
=={{header|XPL0}}==
<
char Two64, Product(40);
[Two64:= "18446744073709551616";
Line 6,311:
Product(39):= Product(39)!$80; \terminate string
Text(0, Product+1); \skip leading zero
]</
Output:
Line 6,320:
=={{header|zkl}}==
[gnu] BigNums are supported via an extension library
<
BN(2).pow(64) * BN(2).pow(64)
340282366920938463463374607431768211456
Line 6,329:
//42!, also BN(42).factorial()
[2..42].reduce(fcn(p,n){p*n},BN(1)) : "%,d".fmt(_)
1,405,006,117,752,879,898,543,142,606,244,511,569,936,384,000,000,000</
{{omit from|Erlang|Erlang has this built in}}
|