1

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
Keerthana
  • 55
  • 7

2 Answers2

1

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

Try a bignum library such as GMP. Here's an example.

#include <gmp.h>
#include <stdio.h>
#include <assert.h>

int main(){

  char inputStr[1024];
  /*
     mpz_t is the type defined for GMP integers.
     It is a pointer to the internals of the GMP integer data structure
   */
  mpz_t n;
  int flag;

  printf ("Enter your number: ");
  scanf("%1023s" , inputStr); /* NOTE: never every write a call scanf ("%s", inputStr);
                                  You are leaving a security hole in your code. */

  /* 1. Initialize the number */
  mpz_init(n);
  mpz_set_ui(n,0);

  /* 2. Parse the input string as a base 10 number */
  flag = mpz_set_str(n,inputStr, 10);
  assert (flag == 0); /* If flag is not 0 then the operation failed */

  /* Print n */
  printf ("n = ");
  mpz_out_str(stdout,10,n);
  printf ("\n");

  /* 3. Add one to the number */

  mpz_add_ui(n,n,1); /* n = n + 1 */

  /* 4. Print the result */

  printf (" n +1 = ");
  mpz_out_str(stdout,10,n);
  printf ("\n");


  /* 5. Square n+1 */

  mpz_mul(n,n,n); /* n = n * n */


  printf (" (n +1)^2 = ");
  mpz_out_str(stdout,10,n);
  printf ("\n");


  /* 6. Clean up the mpz_t handles or else we will leak memory */
  mpz_clear(n);

}
Peter Kapteyn
  • 354
  • 1
  • 13