Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ...

like image 278
CCBet Avatar asked Oct 30 '25 01:10

CCBet


2 Answers

The following types resemble natural numbers set with 0 included in C++:

  • unsigned char
  • unsigned short int
  • unsigned int
  • unsigned long int
  • unsigned long long int, since C++11.

Each one differs with the other in the range of values it can represent.

like image 75
101010 Avatar answered Oct 31 '25 14:10

101010


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).

like image 33
Basile Starynkevitch Avatar answered Oct 31 '25 15:10

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!