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
    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\$ 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
    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
    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.
    Oct 9, 2015 at 2:41

89 Answers 89

24
\$\begingroup\$

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+

\$\endgroup\$
2
  • 3
    \$\begingroup\$ 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.... \$\endgroup\$ Oct 9, 2015 at 1:28
  • 2
    \$\begingroup\$ @quartata Sorry, I haven't updated the docs in a while.. :P \$\endgroup\$
    – Kade
    Oct 9, 2015 at 2:20
13
\$\begingroup\$

Pyth, 6 4 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.

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

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))
\$\endgroup\$
2
  • 3
    \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Oct 8, 2015 at 21:00
  • \$\begingroup\$ What about (a-a*a-~b*b)/2? \$\endgroup\$ Oct 21, 2016 at 12:55
8
\$\begingroup\$

Matlab/Octave, 14 bytes

@(a,b)sum(a:b)
\$\endgroup\$
8
\$\begingroup\$

Julia, 15 bytes

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

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Upvote for a short answer that is completely legible. \$\endgroup\$
    – azz
    Oct 10, 2015 at 4:58
8
\$\begingroup\$

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

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I didn't know you could use lambda's in Javascript! \$\endgroup\$
    – IEatBagels
    Oct 9, 2015 at 13:31
  • 2
    \$\begingroup\$ Oh, it's in the new ES6 specs. \$\endgroup\$ Oct 9, 2015 at 22:49
  • \$\begingroup\$ You can save a byte with currying (a=>b=> …) \$\endgroup\$
    – Cyoce
    Oct 20, 2016 at 21:12
6
\$\begingroup\$

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

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.

\$\endgroup\$
2
  • \$\begingroup\$ Does actually take only one byte in some encoding? \$\endgroup\$ Oct 9, 2015 at 15:06
  • \$\begingroup\$ @RobertoBonvallet I believe APL uses a special encoding \$\endgroup\$
    – Cyoce
    Jan 22, 2016 at 7:25
6
\$\begingroup\$

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);}}
\$\endgroup\$
6
  • 3
    \$\begingroup\$ You really should try something other than Java. ;) \$\endgroup\$ Oct 8, 2015 at 20:57
  • \$\begingroup\$ Would it work to remove the space in int a, int b? Perhaps the space after return as well? \$\endgroup\$
    – Alex A.
    Oct 8, 2015 at 21:17
  • \$\begingroup\$ @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? \$\endgroup\$
    – flawr
    Oct 8, 2015 at 21:24
  • \$\begingroup\$ Even without lambdas, public static isn't usually required for functions here. Just int s(...args...) is fine for the signature. \$\endgroup\$
    – Geobits
    Oct 9, 2015 at 12:45
  • 2
    \$\begingroup\$ you could reduce it by 3 characters, if you use long instead int, i'm talking about full program here \$\endgroup\$
    – user902383
    Oct 20, 2015 at 15:41
6
\$\begingroup\$

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

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,##}&
\$\endgroup\$
5
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ 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 /. \$\endgroup\$
    – cole
    Oct 8, 2015 at 21:53
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – mathmandan
    Oct 9, 2015 at 15:50
5
\$\begingroup\$

R - 24 Bytes

f=function(a,b) sum(a:b)
\$\endgroup\$
3
  • 3
    \$\begingroup\$ You can save yourself 3 by making it an unnamed function and remove the space from it. \$\endgroup\$
    – MickyT
    Oct 9, 2015 at 2:12
  • \$\begingroup\$ 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. \$\endgroup\$
    – Mutador
    Oct 9, 2015 at 4:18
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – Alex A.
    Oct 9, 2015 at 5:15
5
\$\begingroup\$

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

Haskell, 13 bytes

x#y=sum[x..y]

Usage example: 10 # 12 -> 33

\$\endgroup\$
4
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I was trying an O answer, but I forgot about mr and ended up with some REALLY long crap. +1 \$\endgroup\$ Oct 8, 2015 at 22:24
4
\$\begingroup\$

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.

([{({}[()])}{}]{()({}[()])}{})
\$\endgroup\$
0
3
\$\begingroup\$

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

\$\endgroup\$
6
  • \$\begingroup\$ You can save few bytes if you use lambda instead. Requires changing tag to C++11 though. \$\endgroup\$
    – Zereges
    Oct 9, 2015 at 11:35
  • \$\begingroup\$ @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;}? \$\endgroup\$
    – Alex A.
    Oct 9, 2015 at 18:48
  • \$\begingroup\$ yes, exactly like that. Sorry, but I for some reason can address this post to you using @ \$\endgroup\$
    – Zereges
    Oct 9, 2015 at 19:50
  • \$\begingroup\$ @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! :) \$\endgroup\$
    – Alex A.
    Oct 9, 2015 at 19:53
  • \$\begingroup\$ 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) \$\endgroup\$
    – Noodle9
    Oct 11, 2015 at 15:46
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

PowerShell, 32 31 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...

\$\endgroup\$
2
  • \$\begingroup\$ 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, \$\endgroup\$ Oct 9, 2015 at 0:37
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Oct 9, 2015 at 12:48
3
\$\begingroup\$

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

Java, 19 bytes

a->b->a-a*a-b*~b>>1

Thanks to ceilingcat

Try it online!

Explanation

Expand the numerator:

$$(a+b)*(b-a+1) = a*b - a*a + a + b*b - a*b + b = b * b - a * a + a + b$$

>> 1 is equivalent to divide by 2, but it has lower precedence than addition and subtraction, so no parentheses are required. ~x is the same as -x - 1. Thus,

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

Java, 21 bytes

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

Try it online!

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

Jelly, 2 bytes

rS

Try it online.

r   Yields inclusive range [a, b]
 S  Sum
\$\endgroup\$
0
2
\$\begingroup\$

PHP, 29 bytes

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

while($b>=$a)$r+=$b--;echo$r;
\$\endgroup\$
2
\$\begingroup\$

R, 18 Bytes

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

Groovy, 19 Bytes

{a,b->(a..b).sum()}
\$\endgroup\$
2
\$\begingroup\$

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.
\$\endgroup\$
1
  • \$\begingroup\$ Yes, I recognize that on compile, Applescript "helpfully" spaces everything out - this will still compile and run as is, however. \$\endgroup\$ Oct 8, 2015 at 22:51
2
\$\begingroup\$

05AB1E, 2 bytes

ŸO

Explanation:

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Awk, 24 bytes

$0=""($1+$2)*($2-$1+1)/2

Incorporated manatwork's suggestion.

\$\endgroup\$
1
  • \$\begingroup\$ Is shorter if you make it pattern instead of action: $0=""($1+$2)*($2-$1+1)/2. \$\endgroup\$
    – manatwork
    Oct 9, 2015 at 9:51

Your Answer

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