Home > database >  how to add two large unsigned integer in c
how to add two large unsigned integer in c

Time:10-09

so I'm actually trying to do this exercise;

input two integer number, with a >= 1 and b <= 2 power of 32. find the value of a b

I know this is a simple task but the things is, for small numbers value it worked correctly ( like 20 9 = 29), but for value like 1788909566 2626399043 the result is incorrect (it should be 4415308609 but 120341313 came out)

this the code that I worked on :

int main() {
  unsigned int a, b;

  scanf("%u %u", &a, &b);

  printf("%u   %u = %u", a, b, a   b);

  return 0;
}

CodePudding user response:

Always use long long data type while dealing with large numbers."%llu" is the format specifier for long long. unsigned long long int is of 8 bytes and stores number in range of 0 to 18,446,744,073,709,551,615

int main() {
      unsigned long long a, b;
      scanf("%llu %llu" , &a, &b);
      printf("%llu   %llu = %llu", a, b, a   b);
      return 0;
    }

CodePudding user response:

because the result wrapped around. You need to store the result in the larger integer type, or cast to the larger integer type. You need also to use the correct printf format to print unsigned long long number.

int main() {
  unsigned int a, b;

  scanf("%u %u", &a, &b);

  printf("%u   %u = %llu", a, b, (unsigned long long)a   b);

  return 0;
}
int main() {
  unsigned int a, b;
  unsigned long long c;;

  scanf("%u %u", &a, &b);
  c = (unsigned long long)a   b;

  printf("%u   %u = %llu\n", a, b, c);

  return 0;
}
  •  Tags:  
  • c
  • Related