I'm 24 5'1" and recently gainedweight. I'm 155 lbs. How many calories should I eat per day to lose 30-40lbs in a healthy way? How long should it take?

Calories. 120 to 125, could be your best weight. For safety weight control, loss 2 to 4 pounds per week, making exercise, walking is good, reducing carbos, sugar, increases vegetables, some nuts, some fruits, , reducing calories to 1300 per day, check with your pcp or endocrinology your thyroid, liver, kidney, hormones..... More safe and supervised, better results.
1200-1450 cals. Plus a daily aerobic exercise should get you there within a year or less.
2-3 lbs/month. Rapid weight loss usually results in the person gaining back and then some more...I am sure you have seen this before. The trick is to do it slowly so you don't feel you are starving yourself and your body is not under shock due to rapid wt loss. 3500 cal/lb, so figure out how much you are consuming now. If goal = ~3lbs/month, then reduce 10500 cal, or roughly 320cal/day. Good luck...