# 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. Jun 20, 2016 at 14:08
• @BradGilbertb2gills edited for clarity Jun 20, 2016 at 14:20
• This is simpler than it looks ?
– cat
Jun 22, 2016 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 Jun 22, 2016 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, 2016 at 21:17

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

### 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

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.

• ah okay. Could you explain your method though? Jun 20, 2016 at 18:33
• I will, but I'm currently trying to golf it a bit more. Jun 20, 2016 at 18:34
• thanks for the formula. I guess I never saw it like that because we don't cover sums of series like that at school. Pretty interesting though! Jun 20, 2016 at 21:27
• @george I've finished the explanation. Jun 20, 2016 at 22:53
• Wanna tell us a bit more of how in the world the idea to define f came into your mind! The motivation! I'm genuinely interested. Jun 22, 2016 at 14:11

# MATL, 9 bytes

&:&*XRssE


Try it online!

### 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

• I really like seeing the partial results. They really help with understanding the program. Thanks for including them! Jun 20, 2016 at 21:54

## Jelly, 9 8 bytes

rµS²_²S$ Try it online! 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 for a byte!

• For once, Jelly is actually very readable.
Jun 20, 2016 at 14:22
• Can I fork this to my answer? Jun 20, 2016 at 15:08
• @LeakyNun what does that mean? Jun 20, 2016 at 15:17
• This. Jun 20, 2016 at 15:21
• Nice earrings: S²_²S Jun 20, 2016 at 18:22

## 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 nth square pyramidal number, and t(n) be the nth 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.

• Hi could you explain your equation if possible. My python version is 16 bytes longer and I can't figure out how you derived your equation Jun 20, 2016 at 15:06
• @george Let p(n) be the nth square pyramidal number, and t(n) be the nth triangular number. Then this is a simplified version of (t(b)-t(a-1))^2 - (p(b) - p(a-1)). Jun 20, 2016 at 15:11
• @MartinEnder So that is the exact formula that I have used, but Sp3000 has simplified it in a way that I cannot understand. My python script is: (b*-~b-a*~-a)**2/4-(b*-~b*(2*b+1)-a*~-a*(2*a-1))/6 if that is of any use. I have golfed as much as I can the two formula Jun 20, 2016 at 15:15
• @george Sometimes, with problems like these, the easiest way is to get Wolfram|Alpha to do the tedious part, then double checking to make sure it's right. To be honest, I don't think I could have pulled the (a-b-1) factor out of (b*(b+1)*(2b+1)-a*(a-1)*(2a-1))/6 on my own. Jun 21, 2016 at 0:16
• @Sp3000 that's a great way to do it. I'll try that in future Jun 21, 2016 at 5:17

## 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

• Is 05AB1E a ROT13 version of Jelly maybe? Substitute r by Ÿ, µ by D, S by O, ² by n, _ by s and $by -. Jun 20, 2016 at 18:24 • @ThomasWeller: They are quite different actually. A common offset between some "functions" are most likely a coincident. Jelly is a tacit language about chaining functions (afaik), while 05AB1E is a stack based language. Jun 20, 2016 at 18:29 ## 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]. • Would Variance help? Jun 20, 2016 at 14:51 • @LeakyNun I don't see how, because one of the two terms in Variance is divided by n and the other by n^2 and I don't see an easy way to undo those separately. Jun 20, 2016 at 14:53 • Tr@#^2-#.#&@*Range is only 18 bytes. Nov 5, 2018 at 15:58 • @MishaLavrov neat! Feel free to make it a separate answer. :) Nov 5, 2018 at 20:51 ## Labyrinth, 28 24 bytes ?:?:}+=-:(:(#{:**+**#2/!  Try it online! ### 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. ## Haskell, 34 bytes a#b=sum[a..b]^2-sum(map(^2)[a..b])  Usage example: 91 # 123 -> 12087152. Nothing to explain. ## Matlab, 3029 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)  # 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 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. # 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. • Welcome to PPCG! You can probably save a byte by putting that ++ on f+=b*b++ (so you can leave the third slot of the for empty) and you also don't need to square e before returning it (i.e. just do return e*e-f). Jun 20, 2016 at 18:32 • Actually instead of leaving the third slot of the for empty, move the f+=b*b++ in there, so you can save on both a semicolon and the braces. Jun 20, 2016 at 18:34 • Great catch @MartinEnder, thank you :) Jun 20, 2016 at 18:51 • Also based on what Martin had in mind, this seems to be a bit shorter. Jun 20, 2016 at 18:59 • Apparently, my last comment was incorrect. It is actually a special part of the Java grammar: the final statement of a for is actually a special kind of statement, which is called a statement expression list. This special statement can have more than one statement joined by a comma. See 14.14.1 (you'll have to navigate there yourself, I couldn't find a way to make a more precise link) of the language specification. Jun 20, 2016 at 19:38 # 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  ## 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. • Try using n=>m=>eval(for(s=t=0;n<=m;t+=n++)s+=n*n;t*t-s) Jun 21, 2016 at 15:24 • @MamaFunRoll On the other hand, I could try porting Dennis♦'s Python solution... – Neil Jun 22, 2016 at 12:49 # 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 ]  ## 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$$ • You don't need the parens around i+1. Jul 2, 2018 at 2:50 • Also if you want to talk Haskell and Haskell golfing you can join us in the chat room. Jul 2, 2018 at 2:51 # Perl 6, 36 32 31 bytes {([+]$_=@_[0]..@_[1])²-[+] $_»²} {([+]$_=$^a..$^b)²-[+] $_»²} {[+]($_=$^a..$^b)²-[+] $_»²}  Test it ### 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

• Save a byte moving the assignment and evading parens: {$_=$^a..$^b;.sum²-[+]$_»²} Jul 2, 2018 at 10:39
• 25 bytes: {.sum²-[+] $_»²}o&[..] Nov 5, 2018 at 10:29 # 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  # APL, 23 20 bytes -/+/¨2*⍨{(+/⍵)⍵}⎕..⎕  Works in NARS2000. # MATL, 11 bytes &:ts2^w2^s-  Try it online! 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  # Pyth, 11 bytes s*M-F#^}FQ2  Try it online! 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.  • Nice usage of filter. Though there is already a build-in for this task: s*M.P}FQ2 Jun 20, 2016 at 21:30 # Japt, 10 bytes õV x²aUx ²  Try it # 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.  # Vyxal, 8 bytes ṡ:²∑$∑²ε


Try it Online!

## 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


## CJam, 17 bytes

q~),>_:+2#\2f#:+-


Test it here.

### 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*{)-},::*:+


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

# 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(ef(5)(9))
console.log(ef(91)(123))
console.log(ef(1)(10))

# J, 29 bytes

[:(+/@(^&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.

## Pyke, 11 bytes

h1:Ds]MXXs-


Try it here!

h1:         - inclusive_range(input)
Ds]      -     [^, sum(^)]
MX    -    deep_map(^, <--**2)
s  -   ^[1] = sum(^[1])
- -  ^[0]-^[1]


# Julia, 25 bytes

f(a,b,x=a:b)=sum(x)^2-x'x


This is a function that accepts two integers and returns a 1x1 integer array.

The approach is simple: Construct a UnitRange from the endpoints a and b and call it x, then sum x, square it, and subtract its norm, which is computed as transpose(x) * x.

Try it online! (includes all test cases)

• a\b=-(x=a:b)'x+sum(x)^2 saves a few bytes. Jun 20, 2016 at 21:54

# TI-BASIC, 19 bytes

Prompt N,M
randIntNoRep(N,M
sum(Ans)2-sum(Ans2


randIntNoRep gets the range (shuffled). The rest is pretty self explanatory.