Let's take this opportunity to "read the algorithms" together, in a simple and understandable way!
Here is the relevant part of the bitcoin code:
https://github.com/bitcoin/bitcoin/blob/4b24f6bbb51a40e77fcc7f1010eb14187567bc9a/src/validation.cpp#L1068-L1079The lines we are particular interested in explained below:
int halvings = nHeight / consensusParams.nSubsidyHalvingInterval;
This defines the number of halvings as the current block height divided by the halving interval. The halving interval can be seen here, and is set at 210,000 blocks (
https://github.com/bitcoin/bitcoin/blob/feedb9c84e72e4fff489810a2bbeec09bcda5763/src/chainparams.cpp#L67). So prior to block 210,000, there were 0 halvings. After block 210,000, we were on the 1st halving. After block 420,000, the 2nd halving, and so on.
CAmount nSubsidy = 50 * COIN;
This sets the basic subsidy, or block reward, to 50 BTC (or, more accurately, 5,000,000,000 satoshi).
This shifts the subsidy, expressed in binary, 1 bit to right for every halving. Shifting a binary number one bit to the right is the same as halving that number. So for every halving, the subsidy halves.
So we know the base subsidy was 50 BTC, and every 210,000 blocks it will half. And we also therefore know that the first 210,000 blocks created 210,000 * 50 BTC = 10,500,000 BTC, and each subsequent 210,000 blocks will create half this amount. If we let x = 10,500,000 BTC, then we now want to work out x + x/2 + x/4 + x/8 + x/16 ..... and so on. Knowing that
this infinite series converges on 1, then our series (with the additional x at the start) converges on to 2x. 2x = 21,000,000 BTC.
In reality, the number is slightly less than 21,000,000 BTC (20,999,999.9769 BTC) due to rounding errors since we do not express fractions of a satoshi.