I got this question today in an interview: write a function to calculate the total number of gifts received for any day in the 12 days of christmas song. I wrote a simple function using a for() loop in c#’ish code that worked. Then the interviewer asked me to extend it to any number of days. The conversation then turned to how to optimize the loop. Apparently there’s a cool math trick that will do this within the limits of whatever your integer is. Anyone know what it is and what it’s called? Any language is ok and a reference to the algorithm would be fabuloso.
Answers that use recursion are NOT what I’m looking for.
EDIT: Answer for day 2 is 4 gifts total, not 3 since I will have 2 Trees (1 from today, 1 from yesterday) and 2 partridges. On day 12 I’ll have received a total of 364. I want the formula that lets me input 12 and get 364.
nth day, you get 1 + 2 + 3 + … +n.The sum
1 + 2 + ... + nisn(n+1)/2. So the total number,T(N)is the sum ofn(n+1)/2fornin1..N, whereNis the number of days.Now,
n(n+1)/2 = n^2 / 2 + n / 2, and sum ofn^2fornin1..NisN(N+1)(2N+1)/6, so you get:No loops. No recursion.