large integers

Feb 5, 2012 at 4:59am
Using vector, characters, and strings,
how do I add two very large numbers accurately?

(ask for input of two numbers, output the summation result)

Thank you!
Feb 5, 2012 at 5:09am
How large? Larger than 1.844674407370955e+19?
Feb 5, 2012 at 5:40am
100 digits, integers
Feb 5, 2012 at 5:44am
Maybe http://gmplib.org. I don't know if that is overkill.
Last edited on Feb 5, 2012 at 5:45am
Feb 5, 2012 at 6:00am
is there any way to do it without external lib? i'm only allowed to use iostream, vector, and string
thanks (:
Feb 5, 2012 at 7:29am
Yea of course. You're just gonna have to split it up into smaller strings and keep track of the position of the number each string is. I'm on my phone so I can't really give an example.
Feb 5, 2012 at 10:12am
closed account (D80DSL3A)
It can be done simply with 3 strings.
This sounds like a homework problem though so I'll go light on the details.
Declare 3 strings: strNum1, strNum2 and strSum.

Read the #'s to be added straight into strNum1 and strNum2. Each character holds one digit of each number with the least significant digit (ones) at the end. Find which of these 2 strings is the longest. Let's suppose it's strNum2.

Assign strSum = "0" + strNum2. The extra 0 at the beginning gives space for a final carry.

Iterate through strNum1 (use a for loop) from the end to the beginning. You want to add the digits the same way as doing it by hand on paper (working from the least sig. digit to the most sig. digit).

I suggest using several integer variables within the for loop. If we have:
int digit1, digit2, digitSum, carry = 0;
You can extract the integer value from each character with int = char - '0';
Here's an example for finding digit x:
1
2
3
4
5
digit1 = strNum1[x] - '0';
digit2 = strNum2[x] - '0';
digitSum = digit1 + digit2 + carry;// value of carry from last iteration
carry = digitSum/10;// value of carry for the next iteration
strSum[x] = digitSum%10 + '0';

Hopefully you can get it from there. I may get bashed for giving even that much away!

EDIT: This could be done with just 2 strings. See if you can figure how that would work.
Last edited on Feb 5, 2012 at 10:16am
Topic archived. No new replies allowed.