r/learnprogramming • u/Adventurous-Rabbit52 • 33m ago
Is there a way to do this problem faster using computer programming code?
For the song "Twelve Days of Christmas", if you tallied up all the items you received over 12 days- for example, on the 5th day you received 5 gold rings, and thus would need to add that from day 5 to 12 repeatedly- you would end with a large number of each item by the end of the twelfth day. The first instinct would be to put all this data into Excel, and use SUM functions. With new AI technology, or even computer programming coding in general, is there a faster way to get to the final answer?
0
Upvotes
•
u/No_Report_4781 29m ago
One form of writing a program to handle solving the math uses recursion
•
u/Inevitable_Dance1191 24m ago
I don't want to be mean but "new AI technology" is the last thing you need for a basic math problem. An easy way to solve this is with nested for loops.
•
u/SirCarboy 18m ago
12 x 1
11 x 2
10 x 3
9 x 4
8 x 5
7 x 6
6 x 7
5 x 8
4 x 9
3 x 10
2 x 11
1 x 12
you‘re welcome
•
u/captainAwesomePants 7m ago edited 3m ago
The fastest way is probably to type "how many total gifts in 12 days of christmas" into your search bar and you'll probably learn the answer immediately.
The second fastest way is probably a calculator. Excel's also a good choice. Make a triangle with a row of 12 1s, 11 2s, 10 3s, etc. Sum it all. Works great.
If we slow down and think about it, we can find patterns. Each day's gift follows a pattern. We can work out the pattern. 1 thing for 12 days, 2 things for 11 days, ..., 12 things for one day. You get N things, (13-N) times. So our answer will be the sum of N * (13-N) over the range of N=1 through 12.
We could then generalize this to N(N+1)(N+2)/6, where N is the total number of days.
Let's test that. First day, expected one gift: 123/6 = 1. Yep.
Second day: we get 234/6 = 4. That's the first gift twice, plus 2 turtle doves. Yep, it works.
So if there are N total days of Christmas, your formula's N * (N+1) * (N+2) / 6. Plug in 12 and you've got your answer.
We can also solve this with programming a simulation:
•
u/futur3_pr3s3nt 27m ago
with 'new AI technology', you just ask the AI to write this program for you, and it will.
•
u/johlae 16m ago
In python:
•
u/The-Phantom-Blot 15m ago
"Faster" depends on the context. In this case, you have fixed conditions. Excel is OK and pretty fast. But if you had to write a dynamic solver, or specifically needed it done inside a specific program, then you could use recursive functions to build out an array with the quantities.
•
u/BranchLatter4294 13m ago
It's a great programming exercise.
•
u/mkhanwrites_ 2m ago
This is a very basic partial series sum question. The sum of the first n natural numbers 1 + 2 + ... + n is n*(n+1)/2.
For n = 12, you have 12*(12+1)/2 = 12*13/2 = 156/2 = 78.
To answer you question, to find a "faster way to get to the final answer," it might be worth learning mathematics.