views:

162

answers:

2

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.

+2  A: 

On the n th day, we get 1 + 2 + 3 + ... + n gifts.

Or ... (1 + n) + (2 + n-1) + ...

In other words, (n + 1) * n/2.

Anon.
The question asks for total gifts after N days, not the gifts on the nth day.
Jeff Meatball Yang
That's the number of gifts received on day N itself, not the number of gifts received cumulatively up to day N.
Jonathan Leffler
@Jeff Meatball Yang - +1 for 1st person to understand the question. Everyone upvoting doesn't get it.
No Refunds No Returns
@No Refunds No Returns: Maybe it's not that noone understands the question. Maybe you don't understand the answer or the question is wrong :) Seriously though, people are not giving the full answer, although you should be able to extrapolate from the partial answer. What you actually have is a geometric series where each term happens to be an arithmetic series.
Duncan
+8  A: 
  • On the first day, you get 1.
  • On the second day, you get 1 + 2.
  • On the third day, you get 1 + 2 + 3.
  • ...
  • On nth day, you get 1 + 2 + 3 + ... + n.

The sum 1 + 2 + ... + n is n(n+1)/2. So the total number, T(N) is the sum of n(n+1)/2 for n in 1..N, where N is the number of days.

Now, n(n+1)/2 = n^2 / 2 + n / 2, and sum of n^2 for n in 1..N is N(N+1)(2N+1)/6, so you get:

T(N) = N(N+1)(2N+1)/12 + N(N+1)/4
     = N(N^2 + 3N + 2) / 6

No loops. No recursion.

Alok
+1 for correctly modeling the question.
Jeff Meatball Yang
Easy once you see it. Thanks. And I REALLY love SO. It's my new favorite site.
No Refunds No Returns