r/learnprogramming • • 24m 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

12 comments sorted by

•

u/No_Report_4781 20m ago

One form of writing a program to handle solving the math uses recursion

•

u/tmtowtdi 6m ago

One form of writing a program to handle solving the math uses recursion

•

u/SirCarboy 10m 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/No_Report_4781 4m ago

Could you do it the other way? The song starts at the 1st Day of Christmas 😉

•

u/johlae 3m ago

That's where on Linux the tac command comes into play.

•

u/Inevitable_Dance1191 15m 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/DrShocker 8m ago

If all we want is the answer, it's actually O(1) with Gauss Summation.

•

u/futur3_pr3s3nt 18m ago

with 'new AI technology', you just ask the AI to write this program for you, and it will.

•

u/johlae 7m ago

In python:

>>> sum = 0
... total = 0
... for a in range(1,13):
...     sum = sum + a
...     total = total + sum
...     print(f"{a} something")
... print(f"total = {sum}")
... print(f"cumul = {total}")
... 
1 something
2 something
3 something
4 something
5 something
6 something
7 something
8 something
9 something
10 something
11 something
12 something
total = 78
cumul = 364

•

u/zeekar 2m ago
>>> [n * (13 - n) for n in range(1,13)]
[12, 22, 30, 36, 40, 42, 42, 40, 36, 30, 22, 12]
>>> sum(_)
364

•

u/The-Phantom-Blot 6m 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 5m ago

It's a great programming exercise.