Is there a way to calculate BIG numbers expressed as strings?

  • Thread starter Thread starter Sam Kong
  • Start date Start date
S

Sam Kong

Hello!

I wonder if there's a good way to make a function that calculates 2
big numbers (whole numbers) expressed as strings and return a result
string with the value of a number?

For example:

string MyAdd(string s1, string s2);
s = MyAdd("10", "20"); //=> returns "30"

When the numbers are small, no problem.
However, if the numbers are like
"123456789012345678901234567890123456789012345678901234567890", how
can I convert it to number?
The number is longer than the significance digits of double or
decimal.

TIA.
Sam
 
Look for arbitrary length arithmetics libraries -- there are many free. Or
you can easily make your own for the basic operators, simulating "pen and
paper" calculations.
 
Hi,

Not in the framework.

Of course you can always implement a Add routine, if you need other
operations then it's different :)

maybe you can find some third party module that does that.


cheers,
 
This is very very simple.

Since you are dealing with strings you have a wealth of
conversion function and substring indexing. With a
little imagination and math structuring knowlege you can
easily see that if you are dealing with whole number you
can start from the right side and move to the left adding
2 digits as you go and moving the carry along. ie

"12345678901234567890" + "3333333333333333333"
These numbers would be processed by adding the 2 right
most digits together 0 and 3 yeilding 3. Your result
string is built from the left side then as follows:

myresult := 3;

now the next value: 9 + 3 is 12.... only process 1 digit
(right most) and carry the rest.

mysresult = newDigit + myresult ==> "23"

next comes 3 + 8 and don't forget the carry + 1 goes to
12 so: "223" and a carry...

and so forth. You can easlity generalize this algorithm
to a routine that will do any sized numbers and add
a "find the decimal point" feature for decimals.

hope this helps, if not give an e-mail i'll generalize
the algo for you.
 
Thanks for the reply.

Well... addition may be simple.
But what about multiplication?


Could you send me the general algo, please?

(e-mail address removed)

Thank you.

Sam
 
Back
Top