-2

I want to add some huge numbers which I am gonna input from the keyboard. However I want to input them as a string. I've tried a different way with the ASCII which was written in another answer but it doesn't seem to work. Anyway here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

/* ADDING HUGE NUMBERS */
int addHugeNumbers(char *a1,char *a2,char *res){
    int i,q,e; // k is the add
    int k;
    k=0;
    i=0;
    q=0;
    e=strlen(a1);
    while (i<e-1) //CHECK IF THE FIRST ONE IS ONLY DIGITS
    {
        if (isdigit(a1[i])==0) return 0;
        else i++;
    }
    i=0;
    q=strlen(a2);
    while (i<q-1) //SAME CHECK FOR THE SECOND ONE
    {
        if (isdigit(a2[i])==0) return 0;
        else i++;
    }


    k=atoi(a1)+atoi(a2);
    sprintf(res,"%d",k);    
    puts(res); 
return 1;
}
int main(int argc, char *argv[]) {
    char a1[2000], a2[2000],res[2000];
    fgets(a1,2000,stdin);
    fgets(a2,2000,stdin);
    printf("%d",addHugeNumbers(a1,a2,res));
    return 0;

}

This code works just fine with small numbers (lets say up to 5-6 digits). But then when it comes to bigger numbers (15-16) it gives me wrong answers. Try to add 9999999999999999 + 9999999999999999

George David King
  • 201
  • 3
  • 4
  • 10
  • C has no built-in support for arbitrarily huge numbers. You'll need to write your own handling or use a library for it. [GMP](https://gmplib.org/), perhaps? – user2357112 May 28 '14 at 10:31
  • In this case, you should use a library that can do [arbitrary precision arthematic](http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic), such as [GMP](https://gmplib.org/) – Lee Duhem May 28 '14 at 10:32
  • It's just a+b with validation, no special processing of "huge numbers". You don't even change your *res array. It looks like copy-paste without an attempt of understanting. – Ralor May 28 '14 at 10:36
  • 1
    Use [`strtol()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html) for much better error handling ([`atoi()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/atoi.html) basically has no error handling). – pmg May 28 '14 at 11:03

1 Answers1

0

Rightly said that C has no built-in support for arbitrarily huge numbers.

So if there is really a need to add huge numbers input as strings, then write your own function for summing them up by adding unit digits, tens digits, hundreds digits and so on keeping in mind to accommodate the carry if any.

bhushan
  • 46
  • 1
  • 5