Your goal today is to create a function that takes in a counter and a mathematical expression and outputs the summation from i=0 to i=counter-1. If it helps you can also pass in a function rather than a mathematical expression. Ex:
print summation(100, 'i') #or print summation(100, return_i) >> 5050
Comments:
Anonymous - 10 years, 4 months ago
foldl1 haskell does some great work there
reply permalink
Johnathan - 10 years, 4 months ago
It got overly complex because my for loop was messing up, but this works.
reply permalink
Pufe - 10 years, 4 months ago
Your example does not conform to your definition, if the range is exclusive (does not contain endpoints) then the sum should be 4950. My solution on emacs lisp uses an inclusive range to get the same answer as your example. It also evaluates the function at both endpoints (0 and i)
reply permalink
Nick Krichevsky - 10 years, 4 months ago
Quick and dirty python solution
As noted by Pufe, your example does not show counter-1, but rather just counter. If you were to do just counter, the code would be
reply permalink
David - 10 years, 4 months ago
Function Pointers are cool. I>o<I
I have included a couple use examples. The fact that you could pass in a mathematical expression seems to have been overlooked in the other answers. I opted to pass in a function, since I am not motivated to write a parser for math expressions.
reply permalink
Anonymous - 10 years, 4 months ago
I guess you should have used a more complicated mathematical expression in your example ...
function printSummation(counter, expr) { var sum = 0; for (i=0; i<counter; i++) { var curExpr = expr.replace('i', i); sum += eval(curExpr); }
}
printSummation(2, 'i*2') 2 printSummation(3, 'i*2') 6 printSummation(3, 'i/2') 1.5
I'm wondering, is this even possible in Java?
reply permalink
Anonymous - 10 years, 4 months ago
I think I'm the first person to post a O(1) solution - the rest have been O(n).
This uses Gauss' method from the 1700s, using the observation that numbers can be paired (e.g. in summation(100) = 100+0 + 99+1 + 98+2...)
reply permalink