The 5 is because its a 5 series...BMW uses the numbering to distiguish between saloon sizes and coupes.
1 Series = Small Hatchback
3 Series = Small Premium Saloon
5 Series = Medium Premium Saloon
7 Series = Large luxury barge.
6 Series = Large Coupe (8 has also been used in the past)
It used to be true with the non M models that the last 2 digits in the name indicated the size of engine (i.e 325 = 3 series with a 2.5l engine) but this is no longer strictly true (i.e 335 = 3 series with a 3l twin turbo engine)
The 'M' stands for BMW Motorsport - built in a separate factory to the main models in Munich, and are the high performance end of the range. The 3,5,6, is the series code,as other answers have detailed.