# 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? – Zgarb 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?) – TessellatingHeckler 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? – MickyT 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. – Dennis 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. – Alex A. Oct 9 '15 at 2:41

# PHP, 39 bytes

As usual not even close to the shortest answer:

<?=array_sum(range($argv[1],$argv[2]));


Runs from command line like:

php sum.php 10 20

• Not a wonderfull solution, but +1 for doing the same thing I thought of – Martijn Oct 9 '15 at 8:19
• @Martijn Thanks. I couldn't think of anything shorter even using the calculation ($a+$b)*($b-$a+1)/2 isn't shorter than using the long function names. – insertusernamehere Oct 9 '15 at 10:45
• I base my php answers on register_globals in the old settings, so $_GET['a'] would be accessable via $a, saving bytes – Martijn Oct 9 '15 at 10:59
• @Martijn Yeah, but you can't post any answer that runs in PHP 5.4 or better, right? – insertusernamehere Oct 9 '15 at 11:00
• Nope. 'luckily' I've got a 5.2 test environment so I can apply this. Then again, I cant use the funky new possibilities – Martijn Oct 9 '15 at 11:03

## Swift 2, 27 bytes

Swift seems to be able to infer types much more easily these days...

let f={($0+$1)*($1-$0+1)/2}

Called with f(a, b)

# R, 18 Bytes

sum(scan():scan())


## C++11 lambda, 37 bytes

[&b](int a,int&b){b=(a+b)*(b-a+1)/2;}


Invocation:

int main()
{
int a,b;
std::cin >> a; std::cin >> b;
std::cout << ([&b](int a,int&b){b=(a+b)*(b-a+1)/2;}(a,b),b) << std::endl;
return 0;
}

• Do you really need [&b]? You're still taking it as a reference in the argument list. – kirbyfan64sos Oct 14 '15 at 18:15

## Perl 6 (14 chars / bytes)

The only obvious solution is to create a list from a to b, and then to reduce it with the addition operator.

[+] a..b


That would be a snippet, so let's place it in a pointy block.
( One of the ways to create a lambda expression. )

-> \a, \b { [+] a..b } # 22 chars

->\a,\b{[+] a..b} # 17 chars


Or better yet use a placeholder parameterized block.

{[+] $^a..$^b} # 14 chars


Examples of it's use:

say {[+] $^a..$^b}(4,7) # 22␤

# store it as a subroutine and in a scalar
my &s = my $s = {[+]$^a..$^b}; say s 4,8; # 30␤ say$s.(3,8); # 33␤

say ( {[+] $^a..$^b} for 4,7, 4,8, 3,8, ); # (22 30 33)␤


If you wanted to be cheap, you could modify the parser by adding a list summation operator. Which technically could be considered a new language at that point. Although that would be a made up language so wouldn't be a valid answer anyway.
( This is actually how it might be written in the Rakudo implementation if it was added )

sub prefix:<∑> (+@a) is looser(&[,]) {
[+] @a
}

### new language starts here ###

{∑$^a..$^b} # only 11 chars / 12 bytes in UTF8


( Scoring it with bytes feels wrong because Perl 6 and thus this new anonymous language only deal with graphemes in strings. )

## Minkolang 0.8, 14 bytes (INVALID)

Minkolang was created after this challenge was posted, so I post this answer only in the sense of contributing to a catalog.

nndr-[d1-]$+N.  ### Explanation n input as integer (stack: a) n input as integer (stack: a,b) d duplicate top of stack (stack: a,b,b) r reverses stack (stack: b,b,a) - subtraction (stack: b,b-a) [ starts a For loop that will run b-a times d duplicates top of stack 1- subtracts 1 ] closes For loop (stack: b,b-1,b-2,...,a+1,a)$+    sums the stack
N.    outputs as integer and stops


Try it here.

The formula-based solutions like what I used in my Befunge and ><> answers are 2 and 3 bytes longer, respectively:

nd1-*nd1+*r-2:N.
ndnd3R-1+1R+*2:N.


# Jolf, 4 bytes

Try it here!

usjJ
u    sum of
s   the inclusive range between
jJ two inputs


# PlatyPar, 2 bytes (non-competing)

_s


# jq, 25 characters

(24 characters code + 1 character command line option)

[range(.[0];.[1]+1)]|add


Sample run:

bash-4.3$jq -s '[range(.[0];.[1]+1)]|add' <<< '10 15' 75  ## jq, 27 characters (24 characters code + 3 character penalty) [range(.[0];.[1]+1)]|add  Sample run: bash-4.3$ jq '[range(.[0];.[1]+1)]|add' <<< '[10,15]'
75


On-line test

Not specifically interesting, just the -s option which comes handy here: it interprets raw input as array. (Yes, the code itself is identical in both solutions.)

# Squirrel, 21 bytes

@(a,b)(b-a+1)*(b+a)/2


Creates an anonymous function.

# 05AB1E, 2 bytes

ŸO


Explanation:

      # Implicit input
# Implicit input
Ÿ   # Push [a...b]
O  # Sum list
# Implicit print


Try it online!

# Lua, 40 Bytes

Used the same method as the Javascript answer, but in Lua.

function y(a,b)return(a+b)*(b-a+1)/2 end


You use this as such

y(3, 6) --3 + 4 + 5 + 6 == 18


# Bash + bc, 13 bytes

Even shorter bash solution:

# Symbolic Python, 49 bytes (46 + 3 penalty)

_=(_[_==_]*-~_[_==_]-_[_>_]*~-_[_>_])/-~(_==_)


Try it online!

Anything involving range, len, or loops would be too difficult in Symbolic Python, and so I decided the easiest way was to use the formula:

$$\sum_{r=a}^b r = \frac{b(b+1) - a(a-1)}{2}$$

# 33, 20 bytes

OcaxcmszOcaxaclaz2do


Try it online!

## Explanation

This answer uses the following formula to calculate it: $$a + (a+1) + (a+2) + \cdots + b = {a-a^2+b+b^2 \over 2}$$

O       O            | Get a and b as two integers delimited by whitespace
ca                  | (a                  )
xcm               | (  - a^2            )
sz      la     | (        + (       ))
ca          | (          (b      ))
xac       | (          (  + b^2))
z2d  | (                   ) / 2
o | Print it


# APL(NARS), 8 chars, 16 bytes

{+/⍺..⍵}


test:

  f←{+/⍺..⍵}
1 f 2
3
2 f 10
54


This it is 6 chars but I not find a way to assign a name to it

+/↑../


Using as function 2 3

## Reg (a.k.a Unofficial Keg), 17 bytes

Try it online behavior is unknown.

¿¿ï_'(:|_)(+).


This takes 2 inputs separated by newlines.

## Keg, 7 bytes (SBCS is on Keg wiki)

¿¿ɧ∑+).


Explanation

¿¿#      Two nice inputs
ɧ#     Generate range
∑+)#  Summation (looks quite weird because ∑ translates to (!;|. )
.# Output as integer


TIO

# C preprocessor, 40 bytes

#define S(a,b) (((a)+(b))*((b)-(a)+1)/2)

• This submission doesn't add anything particularly useful, and is similar to multiple submissions already here. What makes your post different? Perhaps adding that would make it a more popular solution. – Conor O'Brien Oct 9 '15 at 16:23
• Is codegolf useful? C/C++ cannot compete with interpreted languages in that way, so avoiding typenames and return keyword was the deal. – renonsz Oct 12 '15 at 6:15

# Bash/GNU, 21 Bytes

expr seq -s" + " $@  called with arguments a and b • seq generates a sequence from a to b, separated by " + " • expr evaluates and prints the resulting expression # gs2, 5 bytes WÉ'Od 57 90 27 4f 64  Read two numbers, dump them on the stack, increment the top one, take the range between them, sum it. # Hassium, 60 Bytes func main(){s=0;for(x=input();x<=input();x++)s+=x;print(s);}  Run online and see expanded here ## Burlesque - 6 bytes per@++ usage: $ echo "10 20" | blsq --stdin "per@++"
165


# DUP, 15 bytes

[^^+^3ø-1+*2/.]


Try it here!

Anonymous lambda. Usage:

1 10[^^+^3ø-1+*2/.]!


# Explanation

Uses the formula (a+b)*(b-a+1)/2.

## Elixir, 37 bytes

fn(a,b)->Enum.reduce(a..b,0,&+/2)end


poster child example for reduce, i guess. allows b > a.

## Seriously, 5 bytes (non-competing)

,u,xΣ


Try it online!

# Pylons, 3 bytes

iks

How it works:

i # Take command line input.
k # Push the inclusive range(stack[-2]..stack[-1])
s # Sum the stack.


# Forth, 27 bytes

0
: f 1+ SWAP DO I + LOOP ;


The parameters much be pushed smallest first. Run like this:

1 4 f .


Try it online

# Detour, 11 bytes

{+(}-!>)*d.


This uses the (a+b)*(b-a+1)/2 formula.

+ encodes (a+b), -!> encodes (b-a+1) (really -(a-b)+1), and *d. multiplies (*) the two together, halves it (d), and outputs it (.). {…} makes two copies of a and b and (…) manipulate where the two copies go so that the result of (a+b) doesn't get fed into the (b-a+1) section.

Try it online!

# J, 11 bytes

-:@<:@-*-@+


This is a tacit verb. Example usage:

    v =: -:@<:@-*-@+
5 v 10
45


This verb is a fork of three verbs: -:@<:@-, *, and -@+. A fork x (f g h) y is equivalent to (x f y) g (x h y). Thus, x (-:@<:@-*-@+) y = (x(-:@<:@-)y) * (x (-@+) y). Likewise, the composition of two verbs x (f @ g) y equals f (x g y). Using this rule, given that <: decrements, and -: divides its argument by two, x(-:@<:@-)y = (x - y - 1)/2 and x(-@+)y = -(x+y). Therefore x(-:@<:@-*-@+)y = (x - y - 1) / 2 * -(x+y), and by moving the sign from -(x+y) to (x-y-1), we get (y - x + 1) / 2 * (x + y).

• Dennis's APL solution translated into J for 7 bytes: +%2%1-- – Jonah Sep 28 '17 at 2:21