-2

I want a variable to represent the number 600851475143 in C but this value is larger than the maximum value of long i.e 2147483647.What data type should I use?

user2757185
  • 91
  • 1
  • 1
  • 5

3 Answers3

4

Use integer type long long.
It is good for at least the range -9223372036854775807 <= x <= +9223372036854775807.

#include <stdio.h>
int main(int argc, char *argv[]) {
  long long big = 600851475143;
  printf("%lld\n", big);  // prints 600851475143
  return 0;
}

Alternatively, one could use int64_t or uint64_t - 64-bit types.


The range mentioned above is the minimal range specified in C11 5.2.4.2.1.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
3

Use an unsigned long. This will allow only numbers >= 0, but it will extend your range. I would make sure that your long type is 64-bit, as this will also extend your range of values.

You can also use gmplib, which is released under the LGPL: http://gmplib.org/

SevenBits
  • 2,836
  • 1
  • 20
  • 33
2

Besides using an arbitrary precision integer math library, as suggested by @H2CO3, which is probably you best bet if you plan to work with such big numbers without worrying for overflows, you should check your compiler/platform documentation for the maximum representable number.

If you don't need signed arithmetic you could use unsigned long or unsigned long long, otherwise signed long long. Keep in mind that the standard doesn't mandate their size exactly, only a minimum is specified (from C99 draft standard - Annex E):

#define LONG_MAX +2147483647
#define LONG_MIN -2147483647
#define LLONG_MAX +9223372036854775807
#define LLONG_MIN -9223372036854775807
// [...]
#define ULONG_MAX 4294967295
#define ULLONG_MAX 18446744073709551615
  • but the size of thoose types it self is implementation defined again, isn't it? Or why on all plattforms i know long's size differs in 32 and 64 bit arch's? – dhein Sep 07 '13 at 17:03
  • 1
    @Zaibis Lorenzo Donati posted the _minimum_. The values are implementation defined, but will _at least_ cover the above range, thus a `long` could be 4 or more 8-bit bytes. – chux - Reinstate Monica Sep 07 '13 at 17:15