Data structure for adding very large numbers?

how will you add numbers such as 1234567890123456789012345678901234567890 that cannot be specified using primitive data types? What data structure will you use?

+4
source share
6 answers

You will need a C library that implements arithmetic of arbitrary precision. There are many to choose from. One popular option is the GNU Multipoint Library .

+4
source

In addition to using libraries such as MAPM and MPIR, you can try to keep them double (if precision is not needed), or minimize your own implementation based on arrays.

Google on C bignum for alternatives.

Perhaps this is a good place to start .

+2
source

If you only want to add integers that your question can talk about, then you can simply use the strings and implement a unique addition using the 2D lookup table. If your requirements are more complex, then as others suggested, you need some kind of library to handle large numbers. Regardless of whether you use one of the existing libraries or collapse your own, you can.

+2
source

I recently used MPFR - Multiple GNU floating point calculations with the correct Rounding library. The API is similar in structure to MAPM, which is quite simple to use in my experience.

However, if you use only integers, you are likely to get better performance from a multiple precision library that has separate integer types (like MAPM), since MPFR is designed for floating point.

+2
source

I am using STACKS . Numbers can be stored on the stack by first placing the digit with the highest place value, so the digit in one place should be on the top of the stack. Lay out two stacks and add numbers from the stacks with a carry, which is initially zero. Click on the digit of the third digit. Repeat until both stacks are empty.

0
source

To add a poor person bonus, you can use the C lines:

 #include <stdio.h> #include <stdlib.h> #include <string.h> char *bigadd(const char *a, const char *b) { size_t alen = strlen(a); size_t blen = strlen(b); size_t clen = (alen > blen) ? alen : blen; char *c = malloc(clen + 2); if (c != NULL) { size_t i = clen; int carry = 0; c[i] = '\0'; while (i > 0) { char digit = (alen ? a[--alen] - '0' : 0) + (blen ? b[--blen] - '0' : 0) + carry; c[--i] = digit - 10 * (carry = digit > '9'); } if (carry) { memmove(c + 1, c, clen + 1); c[0] = '1'; } } return c; } int main(int argc, char *argv[]) { const char *a = argc > 1 ? argv[1] : "123456890123456890123456890"; const char *b = argc > 2 ? argv[2] : "2035864230956204598237409822324"; char *c = bigadd(a, b); printf("%s + %s = %s\n", a, b, c); free(c); return 0; } 
0
source

Source: https://habr.com/ru/post/1299416/


All Articles