David Jondreau Posted August 30, 2013 Posted August 30, 2013 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
eos Posted August 30, 2013 Posted August 30, 2013 So my function is: ( ( 1+x ) * 2 ) / 2 ( x + 1 ) * ( x / 2 ) ?
David Jondreau Posted August 30, 2013 Author Posted August 30, 2013 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!
eos Posted August 30, 2013 Posted August 30, 2013 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.
bruceR Posted August 30, 2013 Posted August 30, 2013 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
David Jondreau Posted August 30, 2013 Author Posted August 30, 2013 Crud, eos, you're right, that was a typo. Parens can make thins clearer...Here's a canard: 6 ÷ 2 ( 1+ 2 ) = ?
Recommended Posts
This topic is 4160 days old. Please don't post here. Open a new topic instead.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now