Difference of the square of the sum

Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

$\left(\sum n\right)^2-\sum n^2$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive. Limits will be whole integers above 0.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

5,9      970
91,123   12087152
1,10     2640

This is usual code-golf, so the shorter the answer the better.

• It took me a while to realize the input was the endpoints of a range. – Brad Gilbert b2gills Jun 20 '16 at 14:08
• @BradGilbertb2gills edited for clarity – george Jun 20 '16 at 14:20
• This is simpler than it looks ? – cat Jun 22 '16 at 20:17
• @cat what do you mean by that? Yes the maths is simple Alevel stuff. But it's all down to how you golf it – george Jun 22 '16 at 20:18
• @george The question and many of the answers make it look like a lot of work, but it's not – cat Jun 22 '16 at 21:17

R - 33 bytes

x=scan():scan();sum(x)^2-sum(x^2)

pass your lower limit to the first scan then your upper limit to the second scan

> Input
> Input
> 2
>> 1…2
>> L*3
>> Each 5 4
>> ∑6
>> ∑4
>> 8*3
>> 9-7
>> Output 10

Try it online!

Julia 0.6, 21 bytes

r->sum(r)^2-sum(r.^2)

Returns an anonymous function that takes a Range, eg f(1:10), which then returns the result.

Try it online!

C (gcc), 67 bytes

f(n,m){double a,b;for(;n<=m;a+=n,b+=pow(n++,2));return pow(a,2)-b;}

Try it online!

Jelly, 6 bytes

rµÄḋḊḤ

Recent improvements to the Jelly language allow a compact implementation of the $g$ function from my Python answer.

Try it online!

How it works

rµÄḋḊḤ  Main link. Arguments: a, b (integers)

r       Range; yield R := [a, ..., b].
µ      Begin a monadic chain with argument R.
Ä     Accumulate; take the cumulative sum of R.
Ḋ   Deque; yield [a+1, ..., b].
ḋ    Take the dot product, ignoring the last term of the cumulative sum.
Ḥ  Unhalve; double the result.

C (gcc), 48 bytes

a,b;f(n,m){for(a=b=0;m/n;a+=n++)b+=n*n;n=a*a-b;}

Try it online!

Red, 70 bytes

func[a b][s: t: 0 until[s: s + a t: a * a + t  b < a: a + 1]s * s - t]

Try it online!

Excel, 60 bytes

=(B1^2+B1-A1^2+A1)^2/4-(2*B1^3+3*B1^2+B1-2*A1^3+3*A1^2-A1)/6

Algebraic reshuffling of more verbose implementation: For inputs a and b:

(B1*(B1+1)-A1*(A1-1))/2          // (Sum of b) - (Sum of a-1)
(  )^2                           //  squared
B1*(B1+1)*(2*B1+1)/6             //  Sum of (b squared)
A1*(A1-1)*(2*A1-1)/6             //  Sum of (a-1 squared)

C# (.NET Core), 62 bytes

(a,b)=>{int x=0,y=0;for(;a<=b;a++){x+=a;y+=a*a;}return x*x-y;}

Try it online!

Ungolfed:

(a, b) => {                 // takes in two integer inputs, delimited by a comma
int x = 0, y = 0;       // initializes x and y
for(; a <= b; a++)      // increment a until a equals b
{
x += a;             // add current a to x
y += a * a;         // add square of current a to y
}
return (x * x) - y;     // return the difference of the square of the sums (x*x) and the sum of the squares (y)
}

PHP, 58 bytes

for([,$p,$q]=$argv;$p<=$q;$s+=$p++)$t+=$p*$p;echo$s*$s-$t; Run with -nr or try it online. Python 3, 66 65 bytes lambda a,b:sum(x*y*2for x in range(a,b+1)for y in range(x+1,b+1)) Try it online! with @Dennis formulae and w/o recursion, yet another Python solution (as I cannot comment @leaky-nun solution (not enough reputation) • This is code-golf, you should try to make your code as short as possible. At least remove the unnecessary whitespaces. Try merging two for loops into one if possible. – user202729 Nov 5 '18 at 15:31 • Sorry @user202729, this is actually my first contribution. I've edited using your comment and reformatted contribution using TIO. – david Nov 5 '18 at 15:52 • Did it for the first and forgot it for the second... thanks @Stephen – david Nov 5 '18 at 15:57 Sidef, 46 44 bytes Translation of: my Factor solution {|a,b|R=a..b;R.map{.sqr}.sum-R.sum.sqr->abs} Try it online! use it like x.run(4, 20) -> 38760 Previous ->(a,b,R=a..b){R.map{.sqr}.sum-R.sum.sqr->abs} longer, explained -> # the next list is a function parameter list (a, b, R = a .. b ) # R is a RangeNum over the a and b { # a Block return # return the whole expression R.map{ |n| # map this Block over the range return n.sqr # squared value }.sum # summed the range - # subtract R.sum.sqr # sum of the range, squared ->abs # call Number.abs on everything on the left-hand side of -> } # ok, we're done Burlesque - 16 bytes r@J++2?^j)S[++?- r@ range J dup ++ sum 2?^ square it j swap )S[ map (square) ++ sum ?- subtract Alternate versions: r@JJ?*++j++S[?-ab r@J++2?^jqS[ms?- r@J++J?*jqS[ms?- r@J++J?*jJ?*++?- r@J)S[++j++S[j?- ^- and this is the art of golfing :(. Rust, 67 bytes |b,e|{let mut t=0;let mut s=0;for i in b..=e{t+=i;s+=i*i;}(t*t)-s}; A closure that takes two integers and returns an integer. Tcl, 76 80 bytes proc S l\ u {while $l<=u {incr Q l append R -l*l incr l} expr Q**2+R} Try it online! Pony, 73 bytes fun f(m:U64,n:U64,s:U64=0):U64=>if m>n then 0 else(2*m*s)+f(m+1,n,m+s)end sort of ungolfed fun apply(m: U64, n: U64, s: U64 = 0): U64 => if m > n then 0 else (2 * m * s) + apply(m + 1, n, m + s) end Port of Neil's JavaScript solution. Aheui (esotope), 108 bytes(36 chars) 방빠방빠쌍다쌍상싸사타빠밤타빠받다파반다받상싸사빠따따다따따받밤따나망히 Try it online! Takes two inputs from user(separated by line feed or whitespace) and print result of following function; $$\f(a,b)=((a-b)\cdot(a-b-1)\cdot(3\cdot(a+b)^2+a-b-2))/12\$$ Java, 95 bytes public int d(int a,int b){int i=a,j,s=0;for(;i<=b;i++)for(j=a;j<=b;j++)s+=i==j?0:i*j;return s;} Ideone it! Python, 62 bytes lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1)) Or, longer: lambda a,b:sum(sum(x*y for y in range(a,b+1)if x-y)for x in range(a,b+1)) Ideone both! • This seems to be 63 bytes? (Did you forget the lambda a,b:?) Anyway, it seems like the naive: lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1)) is a byte shorter, unfortunately. – FryAmTheEggman Jun 20 '16 at 14:16 • I'm not quite sure this works, just ran it against the test and 5,9 yields 995? – george Jun 20 '16 at 14:18 Actually, 11 bytes u@x;♂²Σ@Σ²- Try it online! R, 23 bytes sum(i:j)^2-sum((i:j)^2) Does pretty much what you expect by taking i and j as inputs. • you can save a byte by assigning the range to a variable in the first sum. sum(a<-i:j)^2-sum(a^2) – MickyT Jun 20 '16 at 19:05 • This assumes that the variables i and j are already defined, which makes this a snippet. By default we require all submissions to be either full programs which take input from STDIN and print output to STDOUT, or functions that accept arguments and return values. You can fix this by prepending function(i,j) to the beginning. – Alex A. Jun 20 '16 at 19:46 • In fact, all of your answers on the site thus far appear to be snippets. Please adjust them to be programs or functions accordingly. – Alex A. Jun 20 '16 at 19:48 Actually, 10 bytes u@x;;*@Σ²- Try it online! Explanation: u@x;;*@Σ²- u@x range(a, b+1) ;; two copies * dot product with itself (equal to sum of squares) @Σ² sum remaining copy, square sum - subtract Perl 5.10, 41 bytes map{s+=_,r+=_**2}(<>..<>);says**2-r Input is given on 2 lines, for instance: 61 127 Try it here! CoffeeScript, 49 Bytes f=(n,m,s=0)->if n>m then 0else 2*n*s+f(n+1,m,n+s) Translation of Neil's answer Output: f 91, 123 == 12087152 => true Python 2.7, 82 bytes 85 bytes def a(l, u): c=0 d=0 for e in range(l, u+1): c+=e d+=e**2 return c**2-d Works in base 10. • Currently your answer is invalid (use the test cases to verify it): 1. You forgot to square c 2. You have to subtract the sum of squares from the square of the sum, so c**2-d 3. I suggest to golf your code, and you can count newlines as one byte instead of two 4. I suggest adding a Try it online! link – wastl Jul 9 '18 at 19:32 Julia 0.6, 21 bytes r->2triu(r*r',1)|>sum Try it online! Julia port of Luis Mendo's MATL answer. Comes out to the same bytecount as the other Julia answer by @gggg. Takes a Range similar to that answer, does a matrix multiply of it with its transpose to get all pairwise products in a matrix. Takes the upper triangular portion of that (the 1 argument is to denote the distance from the leading diagonal to start from), multiplies that by 2, and finally sums the values and returns that implicitly. Wolfram Language (Mathematica), 18 bytes Tr@#^2-#.#&@*Range Try it online! Composition of Tr@#^2-#.#& (square of sum minus sum of squares, where sum of squares is implemented via dot product) and Range (list of all integers between the two inputs). If you like seeing the operations in order, Range/*Tr@#^2-#.#& is equivalent. As a bonus, also solves this challenge with no modifications, since Range can either take one argument (giving the range from 1 to the input) or two. (But it's not the most efficient solution possible there.) Bash, 74 65 bytes x=y=0;for i in seq 1 2;{ x=[x+i];y=[y+i*i]; };echo [x*x-y] Try it online! I'm no expert at bash golfing, but this works. Managed to cut 9 bytes just by reading through the bash golfing tips thread • for((i=1;i<=2;x+=i,y+=i*i++)){ :;};echo [x*x-y] saves 15 bytes. – Dennis Nov 23 '18 at 1:37 Tcl, 105 bytes proc d a\ b {while {[incr a]<=b} {set j a while$j<=$b {incr p [expr 2*([incr j]-1)*($a-1)]}} expr$p}

Try it online!

# Tcl, 112 bytes

proc d a\ b {set i [expr $a-1] while $$\ij<$b {incr p [expr 2*[incr j]*$i]}} expr$p}