# Summation from a to b

The program has an input of a and b, and outputs the sum of numbers from a to b, inclusive. Score is in bytes. As always, standard loopholes are disallowed.

If your input is in the format [a,b], +3 bytes

• Can b be smaller than a, and if so, what should the output be? Oct 8 '15 at 20:39
• 4 hours, 25 answers and 46 answer votes after posting, you change it so that b>a must error? Ugh. Is that an allowed codegolf thing? (I guess that's a wrong change as well - or is it intended to be a countdown now?) Oct 9 '15 at 1:27
• You are penalizing people for taking input in the format of [a,b]? Why? How does this improve the question? Oct 9 '15 at 1:41
• The overwhelming consensus regarding defaults for reading several pieces of input is that two integers can be read in list from with no penalty. You can obviously override those defaults in your challenge, but it would be preferable to do so when posting the question, not 5 hours later. In case you didn't know, we have a Sandbox where you can get feedback from the community and iron out the details before posting the actual challenge. Oct 9 '15 at 2:16
• @Hurricane996 [a,b] in concept doesn't always use 2 more bytes than a b. What's meant is a list/vector/pair/whatever you want to call it, which doesn't have to look like [a,b]. Such a collection is a more convenient means of input in some languages rather than two separate inputs. Oct 9 '15 at 2:41

# Stuck, 4 Bytes

I'm amazed Stuck finally is winning something! The inclusive range function checks to see if the top of the stack is a list of length 2, and uses it for the parameters of the range function if so.

t]R+


Input is | separated, as t takes a bunch of inputs separated by |s and places them on the stack. ] just wraps the elements in a list, and lets the range function do it's job.

If that still falls in the penalty, then this works (5 Bytes): ii]R+

• Dammit. I was going to try to make a Stuck solution but the docs on Esolang didn't say that you could use the inclusive range function like that and so I gave up.... Oct 9 '15 at 1:28
• @quartata Sorry, I haven't updated the docs in a while.. :P
Oct 9 '15 at 2:20

# Pyth, 64 bytes + 3 = 7 5 bytes

s}vzQ


Avoids the 3-byte penalty imposed by the new input requirements via an extra byte.

Takes input separated from stdin separated by newlines.

Live demo.

## Python, 26

lambda a,b:(a+b)*(b-a+1)/2


Assumes b>=a. Uses the formula of mean * #summands. The result is a whole number, so it doesn't matter if the / is Python 2's floor division.

Shorter by 2 chars than the direct expression

lambda a,b:sum(range(a,b+1))

• I feel like there should be a char save with ~. Expanding gives the same length (b*b-a*a+a+b)/2. So is -b*~b/2-a*~-a/2.
– xnor
Oct 8 '15 at 21:00
• What about (a-a*a-~b*b)/2? Oct 21 '16 at 12:55

# Matlab/Octave, 14 bytes

@(a,b)sum(a:b)


# Julia, 15 bytes

s(a,b)=sum(a:b)


This creates a function s that sums the range a:b. This assumes ab.

• Upvote for a short answer that is completely legible.
– azz
Oct 10 '15 at 4:58

# Dyalog APL, 8 7 bytes

+÷2÷1--


This is a dyadic function train which is equivalent to

{(⍺+⍵)÷2÷1-⍺-⍵}


Try it online.

### How it works

        ⍝ Left argument: a, right argument: b
- ⍝ Calculate a-b.
1-  ⍝ Subtract the difference from 1 to calculate 1-(a-b) = b-a+1.
2÷    ⍝ Divide 2 by the difference to calculate 2/(b-a+1).
+       ⍝ Calculate a+b.
÷      ⍝ Divide the sum by the quotient to calculate (a+b)/(2/(b-a+1)),
⍝ i.e., (a+b)(b-a+1)/2.


# Javascript ES6, 21 bytes

a=>b=>(a+b)*(b-a+1)/2


Used the same approach to that problem that's almost everywhere: "Add up all of the numbers between 1 and 100, inclusive."

• I didn't know you could use lambda's in Javascript! Oct 9 '15 at 13:31
• Oh, it's in the new ES6 specs. Oct 9 '15 at 22:49
• You can save a byte with currying (a=>b=> …) Oct 20 '16 at 21:12

# Java, 44 42 bytes

An approach I haven't seen here so far: Via gaussian sums you can derive that the sum of all numbers from a to b is (b-a+1)*(b+a)/2

If you only have to implement a function, you could do it in 42 bytes:

int s(int a,int b){return(b-a+1)*(b+a)/2;}


The conventional approach is 3 bytes longer:

int s(int a, int b){for(;b>a;a+=b--);return a;}


A full program is 142 bytes:

public class S{public static void main(String[]a){int n=Integer.parseInt(a[0]),m=Integer.parseInt(a[1]);System.out.println((m-n+1)*(m+n)/2);}}

• You really should try something other than Java. ;) Oct 8 '15 at 20:57
• Would it work to remove the space in int a, int b? Perhaps the space after return as well? Oct 8 '15 at 21:17
• @AlexA. Thanks=) Do you know about the Java8 lambdas? I haven't installed it yet but I think (int a,int b)->(b-a+1)*(b+a)/2 should work as a lambda? Oct 8 '15 at 21:24
• Even without lambdas, public static isn't usually required for functions here. Just int s(...args...) is fine for the signature. Oct 9 '15 at 12:45
• you could reduce it by 3 characters, if you use long instead int, i'm talking about full program here Oct 20 '15 at 15:41

# TI-BASIC, 8 bytes

mean(Ans+Ansmin(ΔList(Ans


Takes input in the form {A,B}.

                      Ans    ; {A,B}
ΔList(       ; {B-A}
min(             ;  B-A
Ans                 ; (B-A)*{A,B}
Ans+                    ; (B-A+1)*{A,B}
mean(                        ; (B-A+1)*(A+B)/2


By comparison, the shortest two-variable solution is 11 bytes:

Prompt A,B
sum(randIntNoRep(A,B   ;random permutation of integers between, inclusive


## Mathematica, 9 bytes

Tr@*Range


This evaluates to an unnamed function taking two integers. I was going to use the built-in Sum, but it's 4 bytes longer:

x~Sum~{x,##}&


## ><>, 14 bytes

This assumes that the stack has already been populated with a and b, so this is basically a function. I'm using this online interpreter which lets you put values onto the stack before the program runs. An extra three bytes for -v (plus a space, for running from a terminal) would put this answer at 17 bytes.

:r:@-1+@+*2,n;


### Explanation:

-v  ab                 (initial stack)
:   abb                duplicates top of stack (b)
r   bba                reverses stack
:   bbaa               duplicates top of stack (a)
@   baba               rotates top three elements clockwise (baa -> aba)
-   ba,(b-a)           subtraction (ba -> b-a)
1+  ba,(b-a+1)         adds 1 (b-a -> b-a+1)
@   (b-a+1),ba         rotates top three elements clockwise
+   (b-a+1),(b+a)      addition (ba -> b+a)
*   (b-a+1)*(b+a)      multiplication
2,  (b-a+1)*(b+a)/2    division by 2 (/ is a mirror, so , is used instead)
n;  <integer, quit>    output top of stack as an integer and quit


This assumes that 0 <= a <= b and uses this closed-form solution (b-a+1)(b+a)/2 to directly calculate the answer.

This code below goes the route of trying to be a full program, but only works for 0 <= a <= b <= 9. That you have to do integer parsing in ><> is annoying. Thanks to Cole, if we assume the input is two single digits, then four bytes can be shaved off. 20 bytes.

ic%:ic%:@$-1+@+*2,n;  The trick is that instead of 68*-, use c% (take the modulus with respect to 12). This will indeed work because 48+x (mod 12) is x (mod 12), which is 0-9 if x is 0-9. • For your second program, you can shave off some bytes by changing 68*- to c% since we only expect input from 0 to 9. EDIT: also, division is ,, not /. – cole Oct 8 '15 at 21:53 • It was not originally clear to me where the number 48 was coming from. I see now that it's because the ASCII codes for the characters 0 through 9 are 48 through 57, but I'm mentioning it in case someone else is mystified. Oct 9 '15 at 15:50 # R - 24 Bytes f=function(a,b) sum(a:b)  • You can save yourself 3 by making it an unnamed function and remove the space from it. Oct 9 '15 at 2:12 • You can save 1 byte because you don't really need the space. Also, is it really necessary to declare a function? I see a lot of submissions that doesn't have them so I am getting confused about it. Oct 9 '15 at 4:18 • @AndréMuta Submissions on this site have to use one of our standard input formats. That means that a and b can be function arguments (as is the case here), they can come from user input like from scan(), or they can be read as command line arguments. Oct 9 '15 at 5:15 ## SH, 16 bytes seq$1 $2|numsum  Where$1 and $2 are the values of two args passed to this program on the command line. numsum is from the num-utils package. Another version that is also 16 bytes is: seq -s+$1 $2|bc  # APL, 9 bytes -⍨/2!⎕+⍳2  Takes input as a two-element list . Set your index origin to 0 (⎕IO←0) before running. This is longer than the answer by @Dennis but in my opinion more stylish. It calculates (B+1 nCr 2)-(A nCr 2) = B(B+1)/2-A(A-1)/2. • Does ⍨ actually take only one byte in some encoding? Oct 9 '15 at 15:06 • @RobertoBonvallet I believe APL uses a special encoding Jan 22 '16 at 7:25 ## CJam, 7 bytes q~),>:+  Test it here. q~ e# Read and eval input, pushing a and b onto the stack. ), e# Increment b and turn into the range [0 1 2 ... b-1 b]. > e# Discard the first a elements to get [a a+1 ... b-1 b]. :+ e# Reduce + onto the list, computing the sum.  # Haskell, 13 bytes x#y=sum[x..y]  Usage example: 10 # 12 -> 33 # O, 8 7 bytes Hjmr]+o  Explanation H Start an array with a number from input j Get input as number mr Range between ] + Sum the array o print it  Try it here • I was trying an O answer, but I forgot about mr and ended up with some REALLY long crap. +1 Oct 8 '15 at 22:24 # Brain-Flak, 32 30 bytes ([{({}[()])}{}]{()({}[()])}{})  Try it online! ## Explanation This uses the triangulation algorithm to calculate T(a-1) and T(b) then pushes the difference. I actually golfed 2 bytes off the existing world record triangulation algorithm while making this solution. To push T(a-1) it uses a modified version of the original algorithm. Instead of the simple: ({}[()])({()({}[()])}{})  I removed both the first ({}[()]) and the (). The reason () was there in the first place was that ({({}[()])}{}) quite conveniently calculates T(n-1) for us so there is no need to decrement if we remove the () This first portion is made negative and put next to the second portion which performs standard triangulation inside of the outer push. ([{({}[()])}{}]{()({}[()])}{})  # C++, 42 bytes As a function (42 bytes): int s(int a,int b){return(a+b)*(b-a+1)/2;}  As a full program that reads from STDIN and writes to STDOUT (86 bytes): #include<iostream> main(){int a,b;std::cin>>a;std::cin>>b;std::cout<<(a+b)*(b-a+1)/2;}  Both approaches compute the sum using the Gaussian formula. Ungolfed: #include <iostream> int s(int a, int b) { return (a + b) * (b - a + 1) / 2; } int main() { int x, y; std::cin >> x; std::cin >> y; std::cout << s(x, y) << std::endl; return 0; }  Try it online • You can save few bytes if you use lambda instead. Requires changing tag to C++11 though. Oct 9 '15 at 11:35 • @Zereges I don't know much about C++ lambdas. Would it be something like [](int a,int b){return(a+b)*(b-a+1)/2;}? Oct 9 '15 at 18:48 • yes, exactly like that. Sorry, but I for some reason can address this post to you using @ Oct 9 '15 at 19:50 • @Zereges You don't need to ping me since this is my post; I'll always get notified of a comment on it. And thanks! :) Oct 9 '15 at 19:53 • You can save 9 bytes from the full program by using std::cin>>a>>b; to get your inout from one line with a space in the middle (eg 1 10) Oct 11 '15 at 15:46 ## Befunge-93, 18 16 bytes &:1-*&:1+*\-2/.@  ### Explanation & a input as integer (a) : aa duplicate top of stack (a -> a,a) 1- a,(a-1) subtract 1 from top of stack (a -> a-1) * a*(a-1) multiply top two values of stack (a,a-1 -> a*(a-1)) & a*(a-1),b input as integer (b) : a*(a-1),bb duplicate top of stack (b -> b,b) 1+ a*(a-1),b,(b+1) add 1 to top of stack (b -> b+1) * a*(a-1),b*(b+1) multiply top two values of stack (b,b+1 -> b*(b+1)) \ b*(b+1),a*(a-1) swap top two values of stack (c,d -> d,c) - b*(b+1)-a*(a-1) subtract top two values of stack (d,c -> d-c) 2/ (b*(b+1),a*(a-1))/2 divide top of stack by 2 .@ <output, exit> output as integer and stop  This uses the following formula: b(b+1) (a-1)(a-1+1) b(b+1) - a(a-1) ------ - ------------ = --------------- 2 2 2  Unfortunately, the shorter (b-a+1)(b+a)/2 cannot be done in Befunge easily because it requires accessing b and a twice, which is impossible to do when working only with the top two values of the stack. Storing a value in "memory" would take more characters. # PowerShell, 3231 29 Bytes $args-join'..'|iex|measure -s


Thanks to TessellatingHeckler for the alternate way to make a range and sum it. Works for any combination of a and b so long as the difference between them is less than 50,000.

Previous version (31):

param($a,$b)($b-$a+1)*($b+$a)/2


Uses the same formula as others, assumes that b>=a.

Previous version (32):

param($a,$b)($a..$b)-join'+'|iex


Pretty trivial. Generates a range of numbers from $a to $b, -joins them with a +, then pipes that to Invoke-Expression which performs the summation. Yay verbosity. Note: This function will break if the two numbers are > 50,000 apart, as that's the (hard-coded) limit of dynamically generated ranges in PowerShell, but it correctly handles b<a, so, y'know...

• I'll throw in $f={$args-join'..'|iex|measure -s} used like & $f 5 10 -> 45 - measuring just the inner function content as you are, it hits 29 bytes. The rules don't say it must only output the sum. Cool idea with the join/iex, Oct 9 '15 at 0:37 • @TessellatingHeckler Oh, interesting. Note that you don't need the $f={ } if you save it as a ps1 file and execute it as a script from the PS command line. Same with the param() versions. That's why I've only ever measured "just the inner function content" because it's a complete program. Oct 9 '15 at 12:48

# Jelly, 2 bytes

rS


Try it online.

Takes two numbers as command-line arguments. This is non-competing since Jelly was created after this challenge.

r   Yields inclusive range [a, b]
S  Sum


# PHP, 29 bytes

Based on standard stricks to set variables (eg register_globals oldSkool)

while($b>=$a)$r+=$b--;echo$r;  # Rust, 27 bytes Creates a closure s that takes two unsigned 8-bit integers and returns another. let s=|m,n|(n-m+1)*(m+n)/2;  # Groovy, 19 Bytes {a,b->(a..b).sum()}  # Applescript, 147 137 Bytes Welp. I'm not winning. set a to(text returned of(display dialog""default answer"")) set b to(text returned of(display dialog""default answer"")) (b-a+1)*(b+a)/2  Since I'd never seen an Applescript answer before, I decided I'd make one, then immediately realized why it never had been done. The explanation is fairly straightforward - set ... to (text returned of (display dialog "" default answer "")) ^ Get the text of ^ the user inputs an answer here (b-a+1)*(b+a)/2 ^ with nothing else below this, Applescript recognizes it as the final value and prints to console.  • Yes, I recognize that on compile, Applescript "helpfully" spaces everything out - this will still compile and run as is, however. Oct 8 '15 at 22:51 # Awk, 24 bytes $0=""($1+$2)*($2-$1+1)/2

Incorporated manatwork's suggestion.

• Is shorter if you make it pattern instead of action: $0=""($1+$2)*($2-\$1+1)/2. Oct 9 '15 at 9:51

# Math++, 23 bytes

?>a
?>b
(b-a+1)*(b+a)/2


### J, 19 bytes

   f=:4 :'+/x+i.1+y-x'
1 f 1
1
1 f 2
3
5 f 10
45


It would be longer if it calculated the answer directly, because it would need some parentheses. I can't quickly find a builtin way to "range from a to b", so it does:

                    # The parameters are x on the left, y on the right
f=:4 : '            # f is a dyad verb defined as...

+/                  # The sum of ...
x +               # x added to the list of ...  (turns 0 1.. to x x+1..)
i.            # the integers from 0 to ...
1+y-x      # 1 + y -x                    (sequence length)

'                    # end definition string.

5 f 10 ->

1 + 10 - 5 =
6

i. 6 =
0 1 2 3 4 5

5 + 0 1 2 3 4 5 =
5 6 7 8 9 10

+/ 5 6 7 8 9 10 =
5 + 6 + 7 + 8 + 9 + 10 =
45

• Have you tried the algorithms from Dennis' and my APL answers? Oct 9 '15 at 0:29
• @ThomasKwa Not yet, I can't even follow them. (Your APL answer has one character which my browser can't render and can't copy into the TryAPL site, one that I can't follow the TryAPL cheat sheet explanation, and I don't know what an index origin is. Dennis's answer - sounds like a train might become a J hook or fork, but I haven't tried to follow what it's doing). Oct 9 '15 at 0:51
• you don't need to count f=: so this is really 16 bytes Sep 28 '17 at 1:32

# Ruby, 22 bytes

->a,b{eval [*a..b]*?+}


Just as long as using the expression in @xnor's Python answer:

->a,b{(a+b)*(b-a+1)/2}


Test it:

->a,b{eval [*a..b]*?+}[10,20] #=> 165

• Not everyone is posting incomplete snippets. When not otherwise specified, one should assume that answers must use one of our default input methods. Oct 8 '15 at 21:01
• @AlexA. yup, but I think the challenge is poorly worded. I'll check back later and update if it's been rephrased. Gotta run. Oct 8 '15 at 21:06