PS7
PS7

Reputation: 87

Sum of very large numbers

So I was wondering how to get sum of very large numbers (10 or more). For example:

number1 = 10481481258125812;
number2 = 10041284812488248;
number3 = 10041248812482488;

I want to add these numbers and store into a variable called sum but I have never worked with such large numbers in C before.

Thank you!

Upvotes: 3

Views: 353

Answers (5)

chqrlie
chqrlie

Reputation: 144695

Type long long is specified as having at least 63 value bits and unsigned long long 64 value bits.

Some compilers (gcc and clang) support even larger integral types with 128 bits as __int128 or __int128_t and __uint128 or __uint128_t. These are non-standard types and the C library usually does not support them, so you would need to write conversion functions to and from strings yourself.

Beyond this, you would require an Arbitrary Precision Arithmetic package such as the GNU multiple precision library.

Upvotes: 0

Abhi_Meruga
Abhi_Meruga

Reputation: 1

unsigned long long can handle such large numbers, up to at least 64 bits:

#include <stdio.h> 

int main() {
    unsigned long long number1 = 10481481258125812;
    unsigned long long number2 = 10041284812488248;
    unsigned long long number3 = 10041248812482488;
    unsigned long long sum = number1 + number2 + number3;
    printf("sum: %llu\n", sum);
}

Upvotes: 0

Idan
Idan

Reputation: 333

Working with a 64bit intiger

If you want to use numbers which are less than 64 bit, you can use int64_t / uint64_t / long long. maximum sizes of these types:

  • int64_t: 2^63 − 1 = 9,223,372,036,854,775,807
  • uint64_t: 2^64 -1 = 18,446,744,073,709,551,615

int64_t and uint64_t are defined at stdint.h

Working with gmplib

If you want to work with even larger number, you can use GMPlib. A simple tutrial: https://www.cs.colorado.edu/~srirams/courses/csci2824-spr14/gmpTutorial.html

Upvotes: 3

Miguel
Miguel

Reputation: 408

Try with this:

#include <stdio.h>
int main ()
{
    long long number1 = 10481481258125812;
    long long number2 = 10041284812488248;
    long long number3 = 10041248812482488;
    long long sum = number1 + number2 + number3;
    printf("sum : %lld",sum);

}

Upvotes: 1

arashka
arashka

Reputation: 1325

Use long long which supports much larger numbers. In some compilers you can use long long long too, but you didn't mention the compiler you are using.

See https://en.wikipedia.org/wiki/C_data_types for more information.

Upvotes: 0

Related Questions