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?

- 91
- 1
- 1
- 5
-
14`unsigned long`? `long long`? `unsigned long long`? Use a bigint library? – Sep 07 '13 at 15:52
-
2...strings? `double`? `long double`? Everything depends on your needs! – nneonneo Sep 07 '13 at 15:55
-
Search for C data types and its sizes. Some even compilers support a 128 bits integer. – The Mask Sep 07 '13 at 16:06
-
You should tell us what are you going to do with that number if you want a better advice. You gave us too little info on the problem you are trrying to solve. – LorenzoDonati4Ukraine-OnStrike Sep 07 '13 at 16:24
3 Answers
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.

- 143,097
- 13
- 135
- 256
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/

- 2,836
- 1
- 20
- 33
-
1Probably a typo, but just to avoid leaving incorrect info in a post: "This will allow only numbers **>= 0**" – LorenzoDonati4Ukraine-OnStrike Sep 07 '13 at 16:20
-
@SevenBits To insure the integer type is 64-bit, simple use `int64_t` or `uint64_t`. – chux - Reinstate Monica Sep 07 '13 at 17:20
-
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

- 6,875
- 4
- 37
- 56
-
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