4
\$\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\$
10
  • 7
    \$\begingroup\$ Can b be smaller than a, and if so, what should the output be? \$\endgroup\$
    – Zgarb
    Commented Oct 8, 2015 at 20:39
  • 26
    \$\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\$ Commented Oct 9, 2015 at 1:27
  • 17
    \$\begingroup\$ You are penalizing people for taking input in the format of [a,b]? Why? How does this improve the question? \$\endgroup\$
    – MickyT
    Commented Oct 9, 2015 at 1:41
  • 29
    \$\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
    Commented Oct 9, 2015 at 2:16
  • 8
    \$\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.
    Commented Oct 9, 2015 at 2:41

89 Answers 89

2
\$\begingroup\$

Vyxal s, 1 byte

Try it Online! (2 bytes flagless)

Explanation:

ṡ  # Push the range from a to b
   # s flag sums the top of the stack
   # Implicitly print 
\$\endgroup\$
1
\$\begingroup\$

Math++, 23 bytes

?>a
?>b
(b-a+1)*(b+a)/2
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ Have you tried the algorithms from Dennis' and my APL answers? \$\endgroup\$
    – lirtosiast
    Commented Oct 9, 2015 at 0:29
  • \$\begingroup\$ @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). \$\endgroup\$ Commented Oct 9, 2015 at 0:51
  • \$\begingroup\$ you don't need to count f=: so this is really 16 bytes \$\endgroup\$
    – Cyoce
    Commented Sep 28, 2017 at 1:32
1
\$\begingroup\$

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 
\$\endgroup\$
2
  • 4
    \$\begingroup\$ Not everyone is posting incomplete snippets. When not otherwise specified, one should assume that answers must use one of our default input methods. \$\endgroup\$
    – Alex A.
    Commented Oct 8, 2015 at 21:01
  • \$\begingroup\$ @AlexA. yup, but I think the challenge is poorly worded. I'll check back later and update if it's been rephrased. Gotta run. \$\endgroup\$
    – daniero
    Commented Oct 8, 2015 at 21:06
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\$
5
  • \$\begingroup\$ Not a wonderfull solution, but +1 for doing the same thing I thought of \$\endgroup\$
    – Martijn
    Commented Oct 9, 2015 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\$ Commented Oct 9, 2015 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
    Commented Oct 9, 2015 at 10:59
  • \$\begingroup\$ @Martijn Yeah, but you can't post any answer that runs in PHP 5.4 or better, right? \$\endgroup\$ Commented Oct 9, 2015 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
    Commented Oct 9, 2015 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\$

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\$
2
  • \$\begingroup\$ Do you really need [&b]? You're still taking it as a reference in the argument list. \$\endgroup\$ Commented Oct 14, 2015 at 18:15
  • \$\begingroup\$ even if it did, [&] is one byte shorter \$\endgroup\$
    – c--
    Commented Aug 8, 2022 at 17:04
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\$
0
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\$

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

J-uby, 9 Bytes

:!~|:/&:+

Explanation:

:!~         generate range a..b
   |        then
    :/&:+   sum it together

Expansion:

:!~|:/&:+
->(a,b){ (:/&:+).(a!~b) }
->(a,b){  :+ / (a !~ b) }
->(a,b){ (a..b).reduce(:+) }
\$\endgroup\$
1
\$\begingroup\$

K (oK), 14 12 bytes

Solution:

+/^/!:'|0 1+

Try it online!

Examples:

> +/^/!:'|0 1+2 7
27
> +/^/!:'|0 1+5 10
45             

Explanation:

Slightly different to doing .5*(x+y)*1+y-x. Instead, calculate ranges, take largest except smallest and then sum up:

+/^/!:'|0 1+ / solution
        0 1+ / vectorised addition of 0 1 / 2 7 -> 2 8
       |     / reverse:                   / 2 8 -> 8 2
    !:'      / til (!:) each (')          / (8;2) -> (0 1 2 3 4 5 6 7;0 1)
  ^/         / except (^) over (/)        / (0 1 2 3 4 5 6 7;0 1) -> 2 3 4 5 6 7
+/           / add (+) over (/) aka sum   / 2 3 4 5 6 7 -> 27
\$\endgroup\$
1
  • \$\begingroup\$ I think 9 bytes is possible with {y+/x_!y} \$\endgroup\$
    – coltim
    Commented Feb 28, 2021 at 16:34
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\$
1
\$\begingroup\$

Desmos, 21 bytes

f(a,b)=(a+b)(b-a+1)/2

Try It On Desmos!

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

Alice, 23 bytes

/@M\-:2*t.{
\MO/.h*2:~{

Try it online!

Flattened

/MM/.h*2:~.t*2:-\O@
/                      Switch to Ordinal
 MM                    Read the two command line arguments
   /                   Back to cardinal
    .h*2:              (a*a+1)/2, the sum of all the integer between 0 and a
         ~             Swap the stack values
          .t*2:        (b*b-1)/2, the sum of all the integer between 0 and b-1
               -       Diff between the two sums
                \      Switch to Ordinal
                 O     Print the result to the output
                  @    Bye
\$\endgroup\$
1
\$\begingroup\$

Knight, 19 bytes

O/*+E=aP=bP+1-b a 2

Try it online!

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

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

Factor + math.unicode, 12 bytes

[ [a,b] Σ ]

Try it online!

Interesting tidbit: sum (and therefore Σ) is a generic (polymorphic) word that specializes on ranges to efficiently calculate arithmetic sums.

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

PlatyPar, 2 bytes

_s

Try it online!

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

C, 32 28 bytes

f(a,b){a=a==b?a:a+f(a+1,b);}

Easier to read

int f(a,b){

  // This ends the recursion by returning the current number
  if(a == b) return a; 

  // This recursively returns the sum of the 
  // current low number and the next low number.
  return a + f(a+1,b);
}
\$\endgroup\$
0
\$\begingroup\$

C preprocessor, 40 bytes

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

\$\endgroup\$
2
  • 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\$ Commented Oct 9, 2015 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
    Commented Oct 12, 2015 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.