—Ever wonder what to do if the integer size required by your program is greater than 232, 264, 2512, 21024? 4294967296 and greater CANNOT be handled by primitive int data type. —What we can do is make use of linked lists. —To Add two such long integers, their digits are traversed from right to left. —The corresponding digits are added and the possible carry is added to the next digit.

—We store the integers from right to left in a list so that the first node contains the least significant digit (rightmost). —And the last node contains the most significant digit (leftmost). —We keep five digits in each node.


  • —First let the user input two long integers
  • —Store the two long integers in the lists
  • —Both lists are traversed in parallel, and five digits are added at a time
  • —If the sum of two 5 digits number is x, the lower order 5 digits of x can be extracted by using
    •   x % 100000
  • —The carry can be computed by integer division
    •   x / 100000
largeInt* addint (largeint *int1, largeint *int2)
  Node *p, q;
  int hunthou = 100000;
  int carry, number, total;
  largeint  * sum;	//defined to contain sum of p and q
  sum = new largeint;
  p = int1->Tail->Next;     //p and q point to heads of list
  q = int2->Tail->Next;
  carry = 0;
  //add info of two nodes and previous carry
  total = p->data + q->data + carry;
  //Determine lower order five digits
  number = total % hunthou;
  insertRear(sum, number);
  //determine the carry
  carry = total / hunthou;
  p = p ->next;
  q = q->next
} while ( p != int1->Tail->Next && q != int2->Tail->Next)

while (p != int1->Tail->Next)
  total = p->data + carry;
  number = total % hunthou;
  insertRear(sum, number);
  carry = total / hunthou;
 p = p->next;

while (q != int2->Tail->Next)
  total = q->data + carry;
  number = total % hunthou;
  insertRear(sum, number);
  carry = total / hunthou;
  q = q->next;

if (carry == 1)
  insertRear (sum, carry);

return  sum;
Tagged with: C/C++ languageSource Code

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.