# 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

# 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 Define the function f(x, y, s) recursively as follows. By applying the recurrence relation of f(a, b, 0) a total of b - a times, we can show that. 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? – george Jun 20 '16 at 18:33
• I will, but I'm currently trying to golf it a bit more. – Dennis Jun 20 '16 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! – george Jun 20 '16 at 21:27
• @george I've finished the explanation. – Dennis Jun 20 '16 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. – Musa Al-hassy Jun 22 '16 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! – DanTheMan Jun 20 '16 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. – Adám Jun 20 '16 at 14:22
• Can I fork this to my answer? – Leaky Nun Jun 20 '16 at 15:08
• @LeakyNun what does that mean? – Doorknob Jun 20 '16 at 15:17
• This. – Leaky Nun Jun 20 '16 at 15:21
• Nice earrings: S²_²S – Thomas Weller Jun 20 '16 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 – george Jun 20 '16 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)). – Martin Ender Jun 20 '16 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 – george Jun 20 '16 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. – Sp3000 Jun 21 '16 at 0:16
• @Sp3000 that's a great way to do it. I'll try that in future – george Jun 21 '16 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 -. – Thomas Weller Jun 20 '16 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. – Emigna Jun 20 '16 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? – Leaky Nun Jun 20 '16 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. – Martin Ender Jun 20 '16 at 14:53 • Tr@#^2-#.#&@*Range is only 18 bytes. – Misha Lavrov Nov 5 '18 at 15:58 • @MishaLavrov neat! Feel free to make it a separate answer. :) – Martin Ender Nov 5 '18 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). – Martin Ender Jun 20 '16 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. – Martin Ender Jun 20 '16 at 18:34 • Great catch @MartinEnder, thank you :) – Mario Ishac Jun 20 '16 at 18:51 • Also based on what Martin had in mind, this seems to be a bit shorter. – FryAmTheEggman Jun 20 '16 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. – FryAmTheEggman Jun 20 '16 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) – Mama Fun Roll Jun 21 '16 at 15:24 • @MamaFunRoll On the other hand, I could try porting Dennis♦'s Python solution... – Neil Jun 22 '16 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. – Post Rock Garf Hunter Jul 2 '18 at 2:50 • Also if you want to talk Haskell and Haskell golfing you can join us in the chat room. – Post Rock Garf Hunter Jul 2 '18 at 2:51 # Perl 6, 36 32 31 bytes {([+]$_=@_..@_)²-[+] $_»²} {([+]$_=$^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²-[+]$_»²} – Phil H Jul 2 '18 at 10:39
• 25 bytes: {.sum²-[+] $_»²}o&[..] – nwellnhof Nov 5 '18 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 – Jakube Jun 20 '16 at 21:30 # Japt, 10 bytes õV x²aUx ²  Try it ## 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)} // 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  -   ^ = sum(^)
- -  ^-^


# 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. – Dennis Jun 20 '16 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.

# Fith, 52 bytes

{ 1 + range dup sum 2 pow swap { 2 pow } map sum - }


This is an anonymous function that takes the two numbers on the stack and leaves a single number.

Explanation:

{
1 + range dup      2 ranges from a to b inclusive
sum 2 pow          Sum one and square it
swap               Bring a fresh range to the top
{ 2 pow } map sum  Square every element and sum the list
-                  Subtract
}

• If you like postfix, point-free and stack-based functional prorgamming you might like Factor :D – cat Jun 23 '16 at 13:50

# GeoGebra, 91 bytes

a(x)=(x²+x)/2
b(x)=x³/3+x²/2+x/6
c(x,y)=(a(y)-a(x))²
d(x,y)=b(y)-b(x)
c(x-1,y)-d(x-1,y)


Defines a function (probably e(x,y)) that computes the desired difference.
a(x) calculates the sum of natural numbers between 0 and x.
b(x) calculates the sum of the squares of the natural numbers between 0 and x.
c(x,y) first computes the sum of the natural numbers between x and y, then squares that sum.
d(x,y) calculates the sum of squares between b(x) and b(y).
The last line defines a multi-variable function that finishes the calculation. The function is automatically assigned a name, saving a few bytes.

• Hi, how do I call the function that this defines? I was able to figure out the input at geogebra.org/classic#cas , but couldn't figure out how to find or call the final function. – sundar - Reinstate Monica Jul 2 '18 at 6:27
• @sundar: The last line is an expression in x and y. We could prepend e(x,y)= to give it a name, but to save bytes, we don’t here. GeoGebra automatically assigns the expression a name (probably e, since that’s the next available letter). I don’t have the environment available right now, but I wouldn’t use the CAS pane. The algebra pane and input bar should do the job right. (It’s been a while since I used GGb online; my mental image of it may be outdated.) – Joe Jul 13 '18 at 4:54