Search code examples
clong-integerbigintegerunsigned-integer

Adding large integer values in C


This is a fairly simple question:

How to get 2 unsigned integer values and add them in C for the following input constraint.

0 <= A, B <= 10^98

I know I can take the input as maybe a string but still I had this question in mind.

I have written the below code but it will not be able to take such a big value of 10^98

#include <stdio.h>

int main() {
    unsigned long long int a, b;
    int x = scanf("%llu%llu", &a, &b);
    while (x > 0) {
        printf("%llu\n",(a + b));
        x = scanf("%llu%llu" ,&a, &b);
    }
    return 0;
}

Solution

  • You cannot use regular arithmetic types for this, even unsigned long long only has 64 bits which is much less than required for your purpose.

    Also note that your loop test is incorrect: it should be while (x == 2)

    Here is a small program that can handle numbers with 99 decimal digits:

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