I had a requirement to add very large numbers together in a recent project (we're talking thousands of digits long!) - obviously the AGK2 integer would not suffice, so I wrote a little function to add large numbers stored as strings [EDIT] Got rid of the arrays of INT completely and used some good old string manipulation instead:
function bigadd$(bignum1$,bignum2$)
lookup$ = "01234567890123456789"
bn1len = len(bignum1$)
bn2len = len(bignum2$)
bnwork$=""
` Find the longest of the two numbers for our loop
if bn1len<>bn2len
if bn1len > bn2len
maxlen = bn1len
` pad shorter string with leading zero
for t2 = 1 to maxlen-bn2len
bnwork$ = bnwork$ + "0"
next t2
bignum2$ = bnwork$ + bignum2$
elseif bn1len < bn2len
maxlen = bn2len
` pad shorter string with leading zero
for t2 = 1 to maxlen-bn1len
bnwork$ = bnwork$ + "0"
next t2
bignum1$ = bnwork$ + bignum1$
endif
else
maxlen = bn1len
endif
for t = maxlen to 1 step -1
offset = val(mid(bignum1$,t,1))+val(mid(bignum2$,t,1))
resultchar$ = mid(lookup$,offset+carry+1,1)
result$=result$+resultchar$
if offset+carry >9
carry = 1
else
carry = 0
endif
next t
` Take care of the final carry
if carry = 1
result$=result$+"1"
inc maxlen
endif
` flip the result so it is the right way round
for t = 0 to maxlen
properresult$ = properresult$ + mid(result$,maxlen-t,1)
next t
endfunction properresult$
example usage:
test$ = bigadd$("4599549544412345678912345151413253421234","1000000000012817234681744012345678901234")
Print(test$)
Print(bigadd$("12345","12345"))
I would appreciate any hints on optimisation, and I'd love to know if anyone has a comprehensive suite of very large number functions available (addition, subtraction, multiplication and divide) before I go create them from scratch!