Can you store a 13 digit number in an integer (int) variable in your program?

So kids, we have a requirement to store a 13 digit number in a variable. Which data-type would you choose? Since it is an integer, we declared an integer variable and initialized it with the number value 1234567890123 (13 digits). However, when we printed the variable and saw the output, the number printed in output didn’t look anything like the 13 digit number we defined it to be. What’s wrong! Let’s have a look.

Our program below shows that we declared four variables ‘a’, ‘b’, ‘c’ and ‘d’. Variable ‘a’ is of the data-type “int” and Variable ‘b’ is of the type “long int”. We will come to “long int” later in this post. For now, let’s focus on the variables ‘a’, ‘c’ and ‘d’, which are integers. When we defined the values of ‘a’ to be 1234567890123 and printed it, why did it print 1912276171 in the output? Can you think about it, kids?

variables for kids

Look at the program carefully: it looks like variable ‘c’ with 10 digit number is printed right, but variable ‘d’ with 11 digit number is not printed right. So, does this mean integers cannot handle more than 10 digits? Think about it, children.

Let’s understand what integers are and what they can store.

In all programming languages such as Python,C++, C, Java, and others, integers have 32 bits (or 4 bytes) for storage. Each bit can take two values (1 and 0) and so 32 bits can store 2^32 values. 2^32 is 4294967296. But, since you have to store both negative and positive values and one 0, the range of values that can be stored will be half negative values and half positive values. This means the integer will store 2147483648 negative values (-2147483648 to -1) and 2147483648 positive values (1 to 2147483647) and zero as one value. 

So, you cannot store a higher value than 2^31-1 = 2147483647 in an integer. Let’s check if it is true or not. Let’s declare an integer at 7 less than this number and keep incrementing it and printing it. If you see the output below, once the number was 2147483647, the values started rotating back and starting from negative value -2147483648. The value doesn’t increase to positive 2147483648.

variables for kids

To store higher values in the integer, we make the integer “unsigned”, meaning it will take only positive values and hence the values stored can cross the limit of 2147483647 and can store up to 4294967295 (4294967296 values from 0 to 4294967295). If you see the below output, when we use the unsigned int, the “i: value increases beyond 2147483647.

python variables for kids

In the first program, we used the variable b as  “long int”, the storage allocated is 8 bytes afor a “long int” and not 4 bytes like “int” and hence it can store positive integers upto 2^63-1 (equals 9.2*10^18). And hence it can be used to store a 13 digit number. 

Integers (even unsigned) cannot be used to store a 13 digit number.

Hope this is helpful, thank you.