Search code examples
c++cvariablesintvariable-declaration

Is there a fundamental type for natural numbers in C/C++?


I have a problem in which I need to declare some variables as natural numbers. Which is the propper fundamental type that I should use for variables that should be natural numbers ? Like for integers is int ...


Solution

  • Notice that a computer (and perhaps even the entire universe) is a finite machine; it has a finite (but very large number) of bits (my laptop has probably less than 1015 bits).

    Of course int are not the mathematical integers. On my machine int is a 32 bits signed integer (and long is a 64 bits signed integer), so int-s have only 232 possible values (and that is much less than the infinite cardinal of mathematical integers).

    So a computer can only represent a finite set of numbers, but quite a large one. That is smaller than the infinite set of natural numbers (remember, some of them are not representable on the entire Earth; read about Richard's paradox).

    You might want to use unsigned (same as unsigned int, on my machine represents natural numbers up to 232-1), unsigned long, unsigned long long or (from <stdint.h>) types like uint32_t, uint64_t ... you would get unsigned binary numbers of 32 or 64 bits. Some compilers and implementations might know about uint128_t or something similar.

    If that is not enough, consider using big ints. You could use a library like GMPlib (but even a big computer is not able to represent extremely large natural numbers -with all their bits-..., and your own brain cannot comprehend them neither).