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
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
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
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
f=:
so this is really 16 bytes
\$\endgroup\$
->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
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
($a+$b)*($b-$a+1)/2
isn't shorter than using the long function names.
\$\endgroup\$
Commented
Oct 9, 2015 at 10:45
register_globals
in the old settings, so $_GET['a']
would be accessable via $a
, saving bytes
\$\endgroup\$
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)
[&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;
}
[&b]
? You're still taking it as a reference in the argument list.
\$\endgroup\$
Commented
Oct 14, 2015 at 18:15
[&]
is one byte shorter
\$\endgroup\$
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 was created after this challenge was posted, so I post this answer only in the sense of contributing to a catalog.
nndr-[d1-]$+N.
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
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.
(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
(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
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.)
@(a,b)(b-a+1)*(b+a)/2
Creates an anonymous function.
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
:!~|:/&:+
Explanation:
:!~ generate range a..b
| then
:/&:+ sum it together
Expansion:
:!~|:/&:+
->(a,b){ (:/&:+).(a!~b) }
->(a,b){ :+ / (a !~ b) }
->(a,b){ (a..b).reduce(:+) }
Solution:
+/^/!:'|0 1+
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
_=(_[_==_]*-~_[_==_]-_[_>_]*~-_[_>_])/-~(_==_)
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} $$
OcaxcmszOcaxaclaz2do
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
{+/⍺..⍵}
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
Try it online behavior is unknown.
¿¿ï_'(:|_)(+).
This takes 2 inputs separated by newlines.
/@M\-:2*t.{
\MO/.h*2:~{
/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
math.unicode
, 12 bytes[ [a,b] Σ ]
Interesting tidbit: sum
(and therefore Σ
) is a generic (polymorphic) word that specializes on range
s to efficiently calculate arithmetic sums.
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);
}
#define S(a,b) (((a)+(b))*((b)-(a)+1)/2)
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 expressionWÉ'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.
b
be smaller thana
, and if so, what should the output be? \$\endgroup\$[a,b]
in concept doesn't always use 2 more bytes thana 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\$