[Question]
  [
**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.
Your program/method should return the answer.
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.
  
[Answer]
# Python 2, 43 bytes
```
f=lambda a,b,s=0:b/a and 2*a*s+f(a+1,b,s+a)
```
Test it on [Ideone](http://ideone.com/1iCZ4l).
### How it works
Call the function defined in the specification \$g(a, b)\$. We have that
$$
\newcommand{\sumab}[2]{\sum\_{a \le #1 \le b} #2 \:}
\begin{align}
g(a,b) & = \left( \sumab n n \right)^2 - \sumab n {n^2} \\
& = \sumab {i,j} {ij} - \sumab n {n^2} \\
& = \sumab {i<j} {ij} + \sumab {i=j} {ij} + \sumab {j<i} {ij} - \sumab n {n^2} \\
& = 2 \sumab {j<i} {ij} \\
& = 2 \sumab {i} {\sum\_{a \le i < j} ij} \\
& = \sumab {i} {\left( 2i \sum\_{a \le j < i} j \right)}
\end{align}
$$
Define the function \$f(x, y, s)\$ recursively as follows.
$$ f(x, y, s) =
\begin{cases}
2xs + f(x+1, y, s+x) & \text{ if } x \le y \\
0 & \text{ if} x > y
\end{cases}
$$
By applying the recurrence relation of \$f(a, b, 0)\$ a total of \$b - a\$ times, we can show that:
$$
\begin{align}
f(a, b, 0) & = 2\cdot0 + f(a+1, b, a) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + f(a+2, b, a+(a+1)) \\
& = 2\cdot0 + 2\cdot(a+1)\cdot a + 2\cdot(a+2)\cdot(a+(a+1)) + f(a+3, b, a+(a+1)+(a+2)) \\
& \vdots \\
& = \sumab {i} {\left( 2i \sum\_{a \le j < i} j \right)} + f\left(b+1, b, \sumab j j\right) \\
& = \sumab {i} {\left( 2i \sum\_{a \le j < i} j \right)} \\
& = g(a, b)
\end{align}
$$
This is the function **f** of the implementation. While `b/a` returns a non-zero integer, the code following `and` is executed, thus implementing the recursive definition of **f**.
Once `b/a` reaches **0**, we have that **b > a** and the lambda returns **False = 0**, thus implementing the base case of the definition of **f**.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
&:&*XRssE
```
[**Try it online!**](http://matl.tryitonline.net/#code=JjomKlhSc3NF&input=MQoxMA)
### Explanation
```
&:   % Inclusive range between the two implicit inputs
&*   % Matrix of all pair-wise products
XR   % Upper triangular part of matrix, without the diagonal
ss   % Sum of all elements of the matrix
E    % Multiply by 2. Implicit display
```
### Example
These are the partial results of each line for inputs `5` and `9`:
1. `&:`
```
5 6 7 8 9
```
2. `&:&*`
```
25 30 35 40 45
30 36 42 48 54
35 42 49 56 63
40 48 56 64 72
45 54 63 72 81
```
3. `&:&*XR`
```
0 30 35 40 45
0  0 42 48 54
0  0  0 56 63
0  0  0  0 72
0  0  0  0  0
```
4. `&:&*XRss`
```
485
```
5. `&:&*XRssE`
```
970
```
[Answer]
## Jelly, ~~9~~ 8 bytes
```
rµS²_²S$
```
[Try it online!](http://jelly.tryitonline.net/#code=csK1U8KyX8KyUyQ&input=&args=OTE+MTIz)
```
r         inclusive range from first input to second input
 µ        pass the range to a new monadic chain
  S       the sum
   ²      squared
    _     minus...
     ²S$  the squares summed
```
Thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman) for a byte!
[Answer]
## Python 2, 45 bytes
```
lambda a,b:(a+~b)*(a-b)*(3*(a+b)**2+a-b-2)/12
```
Closed form solution - not the shortest, but I thought it'd be worth posting anyway.
## Explanation
Let `p(n)` be the *n*th [square pyramidal number](https://en.wikipedia.org/wiki/Square_pyramidal_number), and `t(n)` be the *n*th [triangular number](https://en.wikipedia.org/wiki/Triangular_number). Then, for *n* over the range *a*, ..., *b*:
* ∑n = `t(b)-t(a-1)`, and
* ∑n² = `p(b) - p(a-1)`
* So (∑n)²-∑n² = `(t(b)-t(a-1))² - (p(b) - p(a-1))`.
This expression reduces to that in the code.
[Answer]
## 05AB1E, 8 bytes
```
ŸDOnsnO-
```
**Explained**
```
ŸD       # range from a to b, duplicate
  On     # sum and square first range
    s    # swap top 2 elements
     nO  # square and sum 2nd range
       - # take difference
```
[Try it online](http://05ab1e.tryitonline.net/#code=xbhET25zbk8t&input=OTEKMTIz)
[Answer]
## Mathematica, 21 bytes
```
Tr[x=Range@##]^2-x.x&
```
An unnamed function taking two arguments and returning the difference. Usage:
```
Tr[x=Range@##]^2-x.x&[91, 123]
(* 12087152 *)
```
There's three small (and fairly standard) golfing tricks here:
* `##` represents both arguments at once, so that we can use prefix notation for `Range`. `Range@##` is shorthand for `Range[##]` which expands to `Range[a, b]` and gives us an inclusive range as required.
* `Tr` is for *trace* but using it on a vector simply sums that vector, saving three bytes over `Total`.
* `x.x` is a dot product, saving four bytes over `Tr[x^2]`.
[Answer]
## [Labyrinth](https://github.com/m-ender/labyrinth), ~~28~~ 24 bytes
```
?:?:}+=-:(:(#{:**+**#2/!
```
[Try it online!](http://labyrinth.tryitonline.net/#code=Pzo_On0rPS06KDooI3s6KiorKiojMi8h&input=OTEgMTIz)
### Explanation
Since loops tend to be expensive in Labyrinth, I figured the explicit formula should be shortest, as it can be expressed as linear code.
```
Cmd Explanation                 Stacks [ Main | Aux ]
?   Read M.                     [ M | ]
:   Duplicate.                  [ M M | ]
?   Read N.                     [ M M N | ]
:   Duplicate.                  [ M M N N | ]
}   Move copy to aux.           [ M M N | N ]
+   Add.                        [ M (M+N) | N ]
=   Swap tops of stacks.        [ M N | (M+N) ]
-   Subtract.                   [ (M-N) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) | (M+N) ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-1) | (M+N) ]
(   Decrement.                  [ (M-N) (M-N-1) (M-N-2) | (M+N) ]
#   Push stack depth.           [ (M-N) (M-N-1) (M-N-2) 3 | (M+N) ]
{   Pull (M+N) over from aux.   [ (M-N) (M-N-1) (M-N-2) 3 (M+N) | ]
:   Duplicate.                  [ (M-N) (M-N-1) (M-N-2) 3 (M+N) (M+N) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) 3 ((M+N)^2) | ]
*   Multiply.                   [ (M-N) (M-N-1) (M-N-2) (3*(M+N)^2) | ]
+   Add.                        [ (M-N) (M-N-1) (3*(M+N)^2 + M - N - 2) | ]
*   Multiply.                   [ (M-N) ((M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
*   Multiply.                   [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) | ]
#   Push stack depth.           [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 1 | ]
2   Multiply by 10, add 2.      [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)) 12 | ]
/   Divide.                     [ ((M-N)*(M-N-1)*(3*(M+N)^2 + M - N - 2)/12) | ]
!   Print.                      [ | ]
```
The instruction pointer then hits a dead end and has to turn around. When it now encounters `/` it attempts a division by zero (since the bottom of the stack is implicitly filled with zeros), which terminates the program.
[Answer]
## Haskell, 34 bytes
```
a#b=sum[a..b]^2-sum(map(^2)[a..b])
```
Usage example: `91 # 123` -> `12087152`.
Nothing to explain.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 24 bytes
```
:efL:{:2^.}a+S,L+:2^:S-.
```
Expects the 2 numbers in Input as a list, e.g. `[91:123]`.
### Explanation
```
:efL                     Find the list L of all integers in the range given in Input
    :{:2^.}a             Apply squaring to each element of that list
            +S,          Unify S with the sum of the elements of that list
               L+:2^     Sum the elements of L, then square the result
                    :S-. Unify the Output with that number minus S
```
[Answer]
## Matlab, ~~30~~ ~~29~~ 28 bytes
Using Suever's idea of `norm` gives us 2 bytes less
```
@(x,y)sum(x:y)^2-norm(x:y)^2
```
Old (simple) version:
```
@(x,y)sum(x:y)^2-sum((x:y).^2)
```
[Answer]
# Octave, ~~27~~ 23 bytes
```
@(x,y)sum(z=x:y)^2-z*z'
```
Creates an anonymous function named `ans` which accepts two inputs: `ans(lower, upper)`
[**Online Demo**](http://ideone.com/b9zIwP)
**Explanation**
Creates a row vector from `x` to `y` (inclusive) and stores it in `z`. We then sum all the elements using `sum` and square it (`^2`). To compute the sum of the squares, we perform matrix multplication between the row-vector and it's transpose. This will effectively square each element and sum up the result. We then subtract the two.
[Answer]
# Java, ~~84~~ 77 characters, ~~84~~ 77 bytes
7 bytes smaller due to Martin Ender and FryAmTheEggMan, thank you.
`public int a(int b,int c){int e=0,f=0;for(;b<=c;e+=b,f+=b*b++);return e*e-f;}`
Using the three test cases in the original post: <http://ideone.com/q9MZSZ>
Ungolfed:
```
public int g(int b, int c) {
    int e = 0, f = 0;
    for (; b <= c; e += b, f += b * b++);
    return e*e-f;
}
```
Process is fairly self-explanatory. I declared two variables to represent the square of the sums and the sum of the squares and repeatedly incremented them appropiately. Finally, I return the computed difference.
[Answer]
# JavaScript (ES6), 46 bytes
```
f=(x,y,s=0,p=0)=>x<=y?f(x+1,y,s+x,p+x*x):s*s-p
```
[Answer]
## JavaScript (ES6), ~~50~~ 37 bytes
```
f=(n,m,s=0)=>n>m?0:2*n*s+f(n+1,m,n+s)
```
Now a port of @Dennis♦'s Python solution.
[Answer]
# Factor, 48 bytes
```
[ [a,b] [ [ sq ] map sum ] [ sum sq ] bi - abs ]
```
An anonymous function.
```
[ 
  [a,b] ! a range from a to b 
  [ 
    [ sq ] map sum ! anonymous function: map sq over the range and sum the result 
  ] 
  [ sum sq ] ! the same thing, in reverse order
  bi - abs   ! apply both anon funcs to the range, subtract them and abs the result
]
```
[Answer]
## Haskell, 36 bytes
```
m#n=sum[2*i*j|i<-[m..n],j<-[i+1..n]]
```
---
```
λ> m # n = sum [ 2*i*j | i <- [m..n], j <- [i+1..n] ]
λ> 5 # 9
970
λ> 91 # 123
12087152
λ> 1 # 10
2640
```
Note that
$$\left( \sum\_{k=m}^n k \right)^2 - \sum\_{k=m}^n k^2 = \cdots = \sum\_{k\_1=m}^n \sum\_{k\_2=m\\ k\_2 \neq k\_1}^n k\_1 k\_2 = \sum\_{k\_1=m}^n \sum\_{k\_2=k\_1+1}^n 2 \,k\_1 k\_2$$
[Answer]
# [Perl 6](http://perl6.org), ~~36 32~~ 31 bytes
```
~~{([+] $\_=@\_[0]..@\_[1])²-[+] $\_»²}
{([+] $\_=$^a..$^b)²-[+] $\_»²}~~
{[+]($_=$^a..$^b)²-[+] $_»²}
```
[Test it](https://tio.run/##VY7BDsFAFEX38xV3MZGZmDZtUUoqPsJOkGIqjWrLTIXgp2zt@mM1KiQ2L/ed3HffLeQx9etSSZx8ez0ibzWVSo8I2V8w0UYqhGAEYD0RcIRjBH1HvPfAFa7XaZDrOYO@2/MabrDTUM/vGic3WUUaZWh/4j7RrU0Sx5Y6WLmZ5R5hfZ2154wuQ7qIbJsuVrx6WAaBLqtn9bjXcX78FrLGhoJhuJMXNkmyotRcYHiK0lIyKs@FXGu54eC4mkKJwv8zdvvd/MwC9jZRmtzrFw "Perl 6 – Try It Online")
### Explanation:
```
{ # bare block with placeholder parameters $a and $b
  [+](# reduce with &infix:<+>
      # create a range, and store it in $_
      $_ = $^a .. $^b
  )²
  -
  [+] # reduce with &infix:<+>
    # square each element of $_ ( possibly in parallel )
    $_»²
}
```
### Test:
```
#! /usr/bin/env perl6
use v6.c;
use Test;
my @tests = (
  (5,9) => 970,
  (91,123) => 12087152,
  (1,10) => 2640,
);
plan +@tests;
my &diff-sq-of-sum = {[+]($_=$^a..$^b)²-[+] $_»²}
for @tests -> $_ ( :key(@input), :value($expected) ) {
  is diff-sq-of-sum(|@input), $expected, .gist
}
```
```
1..3
ok 1 - (5 9) => 970
ok 2 - (91 123) => 12087152
ok 3 - (1 10) => 2640
```
[Answer]
# [Aheui (esotope)](https://github.com/aheui/pyaheui), 108 bytes(36 chars)
```
방빠방빠쌍다쌍상싸사타빠밤타빠받다파반다받상싸사빠따따다따따받밤따나망히
```
[Try it online!](https://tio.run/##S8xILc38///1hpWvdy6AkG96el93LwGSb5ob33TveNO05m1zA1h2CYwxG6jgbU/P6w0zgAwgF64SJDtlAwgBxSEMoOINYHbTjNfL576d1/H/v6mCJQA "Aheui (esotope) – 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\$
> 
> 
> 
[Answer]
# APL, ~~23~~ 20 bytes
```
-/+/¨2*⍨{(+/⍵)⍵}⎕..⎕
```
Works in NARS2000.
[Answer]
# MATL, 11 bytes
```
&:ts2^w2^s-
```
[Try it online!](http://matl.tryitonline.net/#code=Jjp0czJedzJecy0&input=NQo5)
Explanation:
```
&:           #Create a range from the input
  t          #Duplicate it
   s2^       #Sum it and square it
      w      #swap the two ranges
       2^s   #Square it and sum it
          -  #Take the difference
```
[Answer]
## PowerShell v2+, 47 bytes
Two variations
```
param($n,$m)$n..$m|%{$o+=$_;$p+=$_*$_};$o*$o-$p
$args-join'..'|iex|%{$o+=$_;$p+=$_*$_};$o*$o-$p
```
In both cases we're generating a range with the `..` operator, piping that to a loop `|%{...}`. Each iteration, we're accumulating `$o` and `$p` as either the sum or the sum-of-squares. We then calculate the square-of-sums with `$o*$o` and subtract `$p`. Output is left on the pipeline and printing is implicit.
[Answer]
# Pyth, 11 bytes
```
s*M-F#^}FQ2
```
[Try it online!](http://pyth.herokuapp.com/?code=s%2aM-F%23%5E%7DFQ2&input=91%2C123&debug=0)
```
s*M-F#^}FQ2
       }FQ    Compute the range
      ^   2   Generate all pairs
   -F#        Remove those pairs who have identical elements
 *M           Product of all pairs
s             Sum.
```
[Answer]
# Japt, 10 bytes
```
õV
x²aUx ²
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9VYKeLJhVXggsg==&input=NSw5)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
rµÄḋḊḤ
```
Recent improvements to the Jelly language allow a compact implementation of the \$g\$ function from [my Python answer](https://codegolf.stackexchange.com/a/83369/12012).
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//csK1w4ThuIvhuIrhuKT///85Mf8xMjM "Jelly – 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.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ṡ:²∑$∑²ε
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaE6wrLiiJEk4oiRwrLOtSIsIiIsIjkxXG4xMjMiXQ==)
## How?
```
ṡ:²∑$∑²ε
ṡ        # Inclusive range between (implicit) second input and (implicit) first input
 :       # Duplicate this range
  ²      # Square each of the duplicate
   ∑     # Summate
    $    # Swap so the other range is at the top
     ∑   # Summate
      ²  # Then square
       ε # Absolute difference between the two
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
IDS²s²S-
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWqzxdgg9tKj60KVh3SXFScjFUeMFiUy5LCBMA)
#### Explanation
```
IDS²s²S-  # Implicit input
ID        # Inclusive range; duplicate
  S²      # Sum the list; square the sum
    s     # Swap so the range is back on top
     ²S   # Square each item; sum the list
       -  # Take the difference
          # Implicit output
```
[Answer]
## CJam, 17 bytes
```
q~),>_:+2#\2f#:+-
```
[Test it here.](http://cjam.aditsu.net/#code=q~)%2C%3E_%3A%2B2%23%5C2f%23%3A%2B-&input=91%20123)
### Explanation
```
q~       e# Read and evaluate input, dumping M and N on the stack.
),       e# Increment, create range [0 1 ... N].
>        e# Discard first M elements, yielding [M M+1 ... N].
_        e# Duplicate.
:+2#     e# Sum and square.
\2f#:+   e# Swap with other copy. Square and sum.
-        e# Subtract.
```
Alternatively, one can just sum the products of all distinct pairs (basically multiplying out the square of the sum, and removing squares), but that's a byte longer:
```
q~),>2m*{)-},::*:+
```
[Answer]
# JavaScript (ES6), 67 bytes
```
a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)
```
## Test Suite
```
f=a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)
e=s=>`${s} => ${eval(s[0])}` // template tag format for tests
console.log(e`f(5)(9)`)
console.log(e`f(91)(123)`)
console.log(e`f(1)(10)`)
```
[Answer]
# J, 29 bytes
Port of [Doorknob's Jelly answer](https://codegolf.stackexchange.com/a/83344/48934).
```
[:(+/@(^&2)-~2^~+/)[}.[:i.1+]
```
## Usage
```
>> f = [:(+/@(^&2)-~2^~+/)[}.[:i.1+]
>> 91 f 123x
<< 12087152
```
Where `>>` is STDIN, `<<` is STDOUT, and `x` is for extended precision.
[Answer]
## Pyke, 11 bytes
```
h1:Ds]MXXs-
```
[Try it here!](http://pyke.catbus.co.uk/?code=h1%3ADs%5DMXXs-&input=9%0A5)
```
h1:         - inclusive_range(input)
   Ds]      -     [^, sum(^)]
      MX    -    deep_map(^, <--**2)
         s  -   ^[1] = sum(^[1])
          - -  ^[0]-^[1]
```
]