August 30, 201312 yr I'm sure there's a dead simple way to do this but I can't think of it. I want a calculation, that given a number "x" will return the sum of all integers between 0 and x. I'm only concerned about positive integers. So, Function ( 5 ) will return 5 + 4 + 3 + 2 + 1 = 15. Function ( 6 ) = 21. Any ideas without resorting to a recursive custom function, because elegance. Ah, Google is my friend. I searched for sum of all previous integers and the first hit had this gem: "1 plus N quantity times N divided by 2." So my function is: ( ( 1+x ) * 2 ) / 2
August 30, 201312 yr Author Po-tay-to, po-tah-to. Also: ( x + 1 ) * Floor ( x /2 ) + ( mod ( x ; 2 ) * Ceiling ( x / 2 ) ) Which is a lot easier to do in your head than you may think!
August 30, 201312 yr Po-tay-to, po-tah-to. Yes, yes, just poke fun at me … there simply was a typo in your post: ( ( 1+x ) * 2 ) / 2 should read ( ( 1 + x ) * x ) / 2 … and then I just happen to like symmetrical parentheses better.
August 30, 201312 yr Most of those parentheses are not necessary and don't do anything because the multiplication and division are commutative, the order of operation doesn't matter. All you need is any arrangement of: (X+1) * X / 2
August 30, 201312 yr Author Crud, eos, you're right, that was a typo. Parens can make thins clearer...Here's a canard: 6 ÷ 2 ( 1+ 2 ) = ?
Create an account or sign in to comment