A Mathematical Analysis of Benford's Law and its Generalization