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
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+
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.
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))
~
. Expanding gives the same length (b*b-a*a+a+b)/2
. So is -b*~b/2-a*~-a/2
.
\$\endgroup\$
(a-a*a-~b*b)/2
?
\$\endgroup\$
Commented
Oct 21, 2016 at 12:55
s(a,b)=sum(a:b)
This creates a function s
that sums the range a:b
. This assumes a
≤ b
.
+÷2÷1--
This is a dyadic function train which is equivalent to
{(⍺+⍵)÷2÷1-⍺-⍵}
⍝ 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.
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."
a=>b=> …
)
\$\endgroup\$
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
-⍨/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
.
⍨
actually take only one byte in some encoding?
\$\endgroup\$
Commented
Oct 9, 2015 at 15:06
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);}}
int a, int b
? Perhaps the space after return
as well?
\$\endgroup\$
(int a,int b)->(b-a+1)*(b+a)/2
should work as a lambda?
\$\endgroup\$
public static
isn't usually required for functions here. Just int s(...args...)
is fine for the signature.
\$\endgroup\$
long
instead int
, i'm talking about full program here
\$\endgroup\$
Commented
Oct 20, 2015 at 15:41
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
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,##}&
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;
-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.
68*-
to c%
since we only expect input from 0 to 9. EDIT: also, division is ,
, not /
.
\$\endgroup\$
f=function(a,b) sum(a:b)
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\$
q~),>:+
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.
x#y=sum[x..y]
Usage example: 10 # 12
-> 33
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
mr
and ended up with some REALLY long crap. +1
\$\endgroup\$
Commented
Oct 8, 2015 at 22:24
([{({}[()])}{}]{()({}[()])}{})
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.
([{({}[()])}{}]{()({}[()])}{})
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;
}
C++11
though.
\$\endgroup\$
[](int a,int b){return(a+b)*(b-a+1)/2;}
?
\$\endgroup\$
@
\$\endgroup\$
std::cin>>a>>b;
to get your inout from one line with a space in the middle (eg 1 10
)
\$\endgroup\$
&:1-*&:1+*\-2/.@
& 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.
$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
, -join
s 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...
$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\$
Commented
Oct 9, 2015 at 0:37
$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\$
Commented
Oct 9, 2015 at 12:48
Creates a closure s
that takes two unsigned 8-bit integers and returns another.
let s=|m,n|(n-m+1)*(m+n)/2;
a->b->a-a*a-b*~b>>1
Thanks to ceilingcat
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
a->b->(a+b)*(b-a+1)/2
Based on standard stricks to set variables (eg register_globals oldSkool)
while($b>=$a)$r+=$b--;echo$r;
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.
ŸO
Explanation:
# Implicit input
# Implicit input
Ÿ # Push [a...b]
O # Sum list
# Implicit print
$0=""($1+$2)*($2-$1+1)/2
Incorporated manatwork's suggestion.
$0=""($1+$2)*($2-$1+1)/2
.
\$\endgroup\$
Commented
Oct 9, 2015 at 9:51
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\$