If you've been around for a while, you probably know that all Mastercard credit cards start with 5, and all Visa cards start with 4. Beyond that, there's more math than you realized in credit card numbers. They are not randomly generated. For example, the last number is what's called a "check digit." It's there to make sure the other numbers are correct.
You don’t select this last digit, it is deterministic. The exact mathematic formula for its generation was invented by Hans Peter Luhn, an engineer at IBM in 1954. Originally patented, the algorithm is now in the public domain and a Worldwide standard ISO/IEC 7812-1
Obviously, with just a single check digit, not all errors can be detected (there’s a one in ten chance of a random number having the correct check digit), but the Luhn algorithm is clever in that it detects any single error (getting a single digit wrong), such as swapping the 9 with a 6 in the above example. It also detects almost all* pair-wise switching of two adjacent numbers. These errors are typical common errors people make when transcribing card numbers, so the check digit does a good thing.
An added side benefit is that, as discussed above, there is only a one in ten chance that a randomly generated number has the correct check digit. This provides a small amount of protection from hackers or poorly educated crooks who might attempt to randomly generate and guess credit card numbers.
See the formula for the check digit in action at DataGenetics, and more about how credit card numbers work. Link -Thanks, Nick!