Density perturbations in f(R) gravity theories in metric and Palatini formalisms