5
\$\begingroup\$

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

\$\endgroup\$
  • 6
    \$\begingroup\$ Can b be smaller than a, and if so, what should the output be? \$\endgroup\$ – Zgarb Oct 8 '15 at 20:39
  • 25
    \$\begingroup\$ 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?) \$\endgroup\$ – TessellatingHeckler Oct 9 '15 at 1:27
  • 15
    \$\begingroup\$ You are penalizing people for taking input in the format of [a,b]? Why? How does this improve the question? \$\endgroup\$ – MickyT Oct 9 '15 at 1:41
  • 25
    \$\begingroup\$ 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. \$\endgroup\$ – Dennis Oct 9 '15 at 2:16
  • 6
    \$\begingroup\$ @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. \$\endgroup\$ – Alex A. Oct 9 '15 at 2:41

78 Answers 78

1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Not a wonderfull solution, but +1 for doing the same thing I thought of \$\endgroup\$ – Martijn Oct 9 '15 at 8:19
  • \$\begingroup\$ @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. \$\endgroup\$ – insertusernamehere Oct 9 '15 at 10:45
  • \$\begingroup\$ I base my php answers on register_globals in the old settings, so $_GET['a'] would be accessable via $a, saving bytes \$\endgroup\$ – Martijn Oct 9 '15 at 10:59
  • \$\begingroup\$ @Martijn Yeah, but you can't post any answer that runs in PHP 5.4 or better, right? \$\endgroup\$ – insertusernamehere Oct 9 '15 at 11:00
  • 1
    \$\begingroup\$ Nope. 'luckily' I've got a 5.2 test environment so I can apply this. Then again, I cant use the funky new possibilities \$\endgroup\$ – Martijn Oct 9 '15 at 11:03
1
\$\begingroup\$

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)

\$\endgroup\$
1
\$\begingroup\$

R, 18 Bytes

sum(scan():scan())
\$\endgroup\$
1
\$\begingroup\$

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;
}
\$\endgroup\$
  • \$\begingroup\$ Do you really need [&b]? You're still taking it as a reference in the argument list. \$\endgroup\$ – kirbyfan64sos Oct 14 '15 at 18:15
1
\$\begingroup\$

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. )

\$\endgroup\$
1
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

Jolf, 4 bytes

Try it here!

usjJ
u    sum of
 s   the inclusive range between
  jJ two inputs
\$\endgroup\$
1
\$\begingroup\$

PlatyPar, 2 bytes (non-competing)

_s

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.)

\$\endgroup\$
1
\$\begingroup\$

Squirrel, 21 bytes

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

Creates an anonymous function.

\$\endgroup\$
1
\$\begingroup\$

05AB1E, 2 bytes

ŸO

Explanation:

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Bash + bc, 13 bytes

Even shorter bash solution:

seq -s+ $@|bc

Try it online!

Explanation

seq -s+ $@ called with for example 2 7 prints 2+3+4+5+6+7, this gets piped to bc which evaluates it & prints the result.

\$\endgroup\$
1
\$\begingroup\$

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} $$

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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

Try it online behavior is unknown.

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

This takes 2 inputs separated by newlines.

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

C preprocessor, 40 bytes

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

\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Conor O'Brien Oct 9 '15 at 16:23
  • \$\begingroup\$ Is codegolf useful? C/C++ cannot compete with interpreted languages in that way, so avoiding typenames and return keyword was the deal. \$\endgroup\$ – renonsz Oct 12 '15 at 6:15
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Hassium, 60 Bytes

func main(){s=0;for(x=input();x<=input();x++)s+=x;print(s);}

Run online and see expanded here

\$\endgroup\$
0
\$\begingroup\$

Burlesque - 6 bytes

per@++ usage:

$ echo "10 20" | blsq --stdin "per@++"
165
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Elixir, 37 bytes

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

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

\$\endgroup\$
0
\$\begingroup\$

Seriously, 5 bytes (non-competing)

,u,xΣ

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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).

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy