r/dailyprogrammer_ideas • u/Happydrumstick93 • May 31 '18
[Easy] The sum function
Description
The sum function is a commonly used function in programming. You might want to sum up all the values in a list, the sum function achieves this; implement the sum function.
Input
[1,2,3]
Output
6
Challenge 1
Summing must be done in O(1) time. Not only that but it must also be doable between arbitrary bounds.
example input
[20, 21 .. 100]
example output
4860
Challenge 2
Create a higher order sum function which takes an inverse function (anti-function), a list, and computes in O(1) time complexity. Thus allowing you to sum up any list that could be constructed using a linear function such as y=nx with the anti-function a=x/n.
So for a list of even numbers you would need to pass in (\x.(x/2)).
Example input
sum([0, 2 .. 100000000000], (lambda x:(x/2)))
Output
2.50000000005e+21
Hint: Maths!
View all comments
Show parent comment
1
u/Happydrumstick93 May 31 '18 edited May 31 '18
Yes I'm aware. Where is the loop:
(s + e)*(a( e - s )+1)/2
edit:
Like I said the very first problem laid out was just make a sum function, this could be done using
This is intended to get absolute beginners into programming. The challenge (challenge 1) uses algebra. in the form of (e-s+1)/2 * (e+s). So [1,2,3,4,5,6,7,8,9,10] would be (10-1+1)/2 * 11 = 5*11 = 55.
The second challenge (challenge 2) was meant to generalise further, using the form (s + e)*(a( e - s )+1)/2 where a is the anti-function, but I realised (thanks to your comment) that this doesn't generalise to non-linear functions, and thus could only be done with y=nx. Such as [5,10,15..], [3,6,9,12 ..]