As per many posts above, it all has to do with practical limitations, and remember that the original AR/M16 magazine was 20 rounds, as well.
That said, the M16 mag was probably (admittedly guessing) 20 rounds because that was a commonly accepted number for a magazine 50 years ago, based on the M14/FN. 20 rounds was a lot for normal rate fire, especially if you carried 5+mags. However, obviously a 5.56 was smaller than a 7.62, so it likely did not take that long for someone to realize that you could carry more rounds in a 5.56 mag before you're at the weight that a 7.62 mag had been.
Since that time, the number for AR platforms went up to a number that is generally 30 for common-sense reasons. It gives the shooter more rounds while still not being impractical. A soldier can still lift and handle a full 30 round mag without issue, and it still fits well in their kit. Further, anything longer than a 30-round mag, and it is starting to get ridiculously long hanging out of the bottom of the rifle, and it may not be possible for a short person to fire from the prone because their forearms aren't long enough.
As to why it is not a more precisely perfect number, like why not 28 or 32? The reason is likely due to logistical and simple math reasons. Ammo comes to troops in small cardboard boxes of 30 rounds-per-box, in 3x 10-round clips, which is a nice round number that is easy to load with a mag charger. I suppose it could just as easily be in 3x9 or 3x11 round boxes, but under contact it's a lot easier to do the math of how many rounds you have left, or how many you need, when you're figuring out 5x30, 10x30, or "I need 2x30".