Long multiplication: Difference between revisions
Content added Content deleted
m (Long multiplication in Run BASIC) |
(Long multiplication in BASIC-256) |
||
Line 1,413: | Line 1,413: | ||
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 |
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</syntaxhighlight> |
720 RETURN</syntaxhighlight> |
||
=={{header|BASIC256}}== |
|||
{{trans|Liberty BASIC}} |
|||
<syntaxhighlight lang="freebasic">print "2^64" |
|||
a$ = "1" |
|||
for i = 1 to 64 |
|||
a$ = multByD$(a$, 2) |
|||
next |
|||
print a$ |
|||
print "(check with native BASIC-256)" |
|||
print 2^64 |
|||
print "(looks OK)" |
|||
#now let's do b$*a$ stuff |
|||
print |
|||
print "2^64*2^64" |
|||
print longMult$(a$, a$) |
|||
print "(check with native BASIC-256)" |
|||
print 2^64*2^64 |
|||
print "(looks OK)" |
|||
end |
|||
function max(a, b) |
|||
if a > b then |
|||
return a |
|||
else |
|||
return b |
|||
end if |
|||
end function |
|||
function longMult$(a$, b$) |
|||
signA = 1 |
|||
if left(a$,1) = "-" then |
|||
a$ = mid(a$,2,1) |
|||
signA = -1 |
|||
end if |
|||
signB = 1 |
|||
if left(b$,1) = "-" then |
|||
b$ = mid(b$,2,1) |
|||
signB = -1 |
|||
end if |
|||
c$ = "" |
|||
t$ = "" |
|||
shift$ = "" |
|||
for i = length(a$) to 1 step -1 |
|||
d = fromradix((mid(a$,i,1)),10) |
|||
t$ = multByD$(b$, d) |
|||
c$ = addLong$(c$, t$+shift$) |
|||
shift$ += "0" |
|||
next |
|||
if signA * signB < 0 then c$ = "-" + c$ |
|||
return c$ |
|||
end function |
|||
function multByD$(a$, d) |
|||
#multiply a$ by digit d |
|||
c$ = "" |
|||
carry = 0 |
|||
for i = length(a$) to 1 step -1 |
|||
a = fromradix((mid(a$,i,1)),10) |
|||
c = a * d + carry |
|||
carry = int(c/10) |
|||
c = c mod 10 |
|||
c$ = string(c) + c$ |
|||
next |
|||
if carry > 0 then c$ = string(carry) + c$ |
|||
return c$ |
|||
end function |
|||
function addLong$(a$, b$) |
|||
#add a$ + b$, for now only positive |
|||
l = max(length(a$), length(b$)) |
|||
a$ = pad$(a$,l) |
|||
b$ = pad$(b$,l) |
|||
c$ = "" #result |
|||
carry = 0 |
|||
for i = l to 1 step -1 |
|||
a = fromradix((mid(a$,i,1)),10) |
|||
b = fromradix((mid(b$,i,1)),10) |
|||
c = a + b + carry |
|||
carry = int(c/10) |
|||
c = c mod 10 |
|||
c$ = string(c) + c$ |
|||
next |
|||
if carry > 0 then c$ = string(carry) + c$ |
|||
return c$ |
|||
end function |
|||
function pad$(a$,n) #pad$ from right with 0 to length n |
|||
pad$ = a$ |
|||
while length(pad$) < n |
|||
pad$ = "0" + pad$ |
|||
end while |
|||
end function |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>2^64 |
|||
18446744073709551616 |
|||
(check with native BASIC-256) |
|||
1.84467440737e+19 |
|||
(looks OK) |
|||
2^64*2^64 |
|||
340282366920938463463374607431768211456 |
|||
(check with native BASIC-256) |
|||
3.40282366921e+38 |
|||
(looks OK)</pre> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |