# Sum square difference

The sum of the squares of the first ten natural numbers is, $$\1^2 + 2^2 + \dots + 10^2 = 385\$$

The square of the sum of the first ten natural numbers is,

$$\(1 + 2 + ... + 10)^2 = 55^2 = 3025\$$

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is

$$\3025 − 385 = 2640\$$

For a given input n, find the difference between the sum of the squares of the first n natural numbers and the square of the sum.

Test cases

1       => 0
2       => 4
3       => 22
10      => 2640
24      => 85100
100     => 25164150


This challenge was first announced at Project Euler #6.

### Winning Criteria

• There are no rules about what should be the behavior with negative or zero input.

• This challenge needs a winning criterion (e.g. code golf) Nov 4, 2018 at 19:25
• This is a subset of this question Nov 4, 2018 at 19:45
• Can the sequence be 0 indexed? i.e. the natural numbers up to n?
– Jo King
Nov 4, 2018 at 23:49
• Nov 5, 2018 at 5:53
• @Enigma I really don't think that this is a duplicate of the target since many answers here don't port easily to be answers of that, so this adds something. Nov 5, 2018 at 8:33

# Jelly,  5  4 bytes

Ḋ²ḋṖ


Try it online!

### How?

Implements $$\\sum_{i=2}^n{(i^2(i-1))}\$$...

Ḋ²ḋṖ - Link: non-negative integer, n
Ḋ    - dequeue (implicit range)       [2,3,4,5,...,n]
²   - square (vectorises)            [4,9,16,25,...,n*n]
Ṗ - pop (implicit range)           [1,2,3,4,...,n-1]
ḋ  - dot product                    4*1+9*2+16*3+25*4+...+n*n*(n-1)


# Python 3,  28  27 bytes

-1 thanks to xnor

lambda n:(n**3-n)*(n/4+1/6)


Try it online!

Implements $$\n(n-1)(n+1)(3n+2)/12\$$

Python 2,  29  28 bytes: lambda n:(n**3-n)*(3*n+2)/12

• You can shave a byte with n*~-n**2* or (n**3-n)*.
– xnor
Nov 5, 2018 at 0:33

# APL (Dyalog Unicode), 10 bytes

1⊥⍳×⍳×1-⍨⍳


Try it online!

### How it works

1⊥⍳×⍳×1-⍨⍳
⍳×⍳×1-⍨⍳  Compute (x^3 - x^2) for 1..n
1⊥          Sum


Uses the fact that "square of sum" is equal to "sum of cubes".

• For me 1⊥⍳×⍳×1-⍨⍳ is not a function ; I tried 1⊥⍳×⍳×1-⍨⍳10 and for me not compile...
– user58988
Nov 5, 2018 at 13:32
• @RosLuP You have to assign it to a variable first (as I did in the TIO link) or wrap it inside a pair of parentheses, as (1⊥⍳×⍳×1-⍨⍳)10. Nov 5, 2018 at 23:10

# TI-Basic (TI-83 series), 12 11 bytes

sum(Ans² nCr 2/{2,3Ans


Implements $$\\binom{n^2}{2}(\frac12 + \frac1{3n})\$$. Takes input in Ans: for example, run 10:prgmX to compute the result for input 10.

• Nice use of nCr!
– Lynn
Nov 5, 2018 at 12:42

# Brain-Flak, 747268 64 bytes

((([{}])){({}())}{})([{({}())({})}{}]{(({}())){({})({}())}{}}{})


Try it online!

Pretty simple way of doing it with a couple of tricky shifts. Hopefully someone will find some more tricks to make this even shorter.

# Japt -x, 985 4 bytes

õ²í*


Try it

## Explanation

õ        :Range [1,input]
²       :Square each
í      :Interleave with 0-based indices
*     :Reduce each pair by multiplication
:Implicit output of the sum of the resulting array


# JavaScript, 20 bytes

f=n=>n&&n*n*--n+f(n)


Try it online

• what deviltry is this May 14, 2019 at 3:10

# Charcoal, 12 10 bytes

ＩΣＥＮ×ιＸ⊕ι²


Try it online! Link is to verbose version of code. Explanation: $$\ ( \sum_1^n x )^2 = \sum_1^n x^3 \$$ so $$\ ( \sum_1^n x )^2 - \sum_1^n x^2 = \sum_1^n (x^3 - x^2) = \sum_1^n (x - 1)x^2 = \sum_0^{n-1} x(x + 1)^2 \$$.

   Ｎ        Input number
Ｅ         Map over implicit range i.e. 0 .. n - 1
ι   Current value
⊕    Incremented
²  Literal 2
Ｘ     Power
ι      Current value
×       Multiply
Σ          Sum
Ｉ           Cast to string
Implicitly print


# Perl 6, 22 bytes

{sum (1..$_)>>²Z*^$_}


Try it online!

Uses the construction $$\ \sum_{i=1}^n {(i^2(i-1))} \$$

# dc, 16 bytes

?dd3^r-r3*2+*C/p


Implements $$\(n^3-n)(3n+2)/12\$$

Try it online!

# APL(Dyalog), 17 bytes

{+/(¯1↓⍵)×1↓×⍨⍵}⍳


(Much longer) Port of Jonathan Allan's Jelly answer.

Try it online!

• Go tacit and combine the drops: +/¯1↓⍳×1⌽⍳×⍳
Nov 5, 2018 at 15:50

# APL (Dyalog), 16 bytes

((×⍨+/)-(+/×⍨))⍳


Try it online!

 (×⍨+/)            The square (× self) of the sum (+ fold)
-           minus
(+/×⍨)     the sum of the square
(             )⍳   of [1, 2, … input].

• (+/×⍨)1⊥×⍨ as per tip.
Nov 5, 2018 at 15:46
• A further byte could be saved by keeping the ⍳ inside (×⍨1⊥⍳)-⍳+.×⍳ Nov 5, 2018 at 18:43

# Mathematica, 21 17 bytes

-4 bytes thanks to alephalpha.

(3#+2)(#^3-#)/12&


Pure function. Takes an integer as input and returns an integer as output. Just implements the polynomial, since Sums, Ranges, Trs, etc. take up a lot of bytes.

• (3#+2)(#^3-#)/12& Nov 5, 2018 at 4:43
• It's possible to get there without just evaluating the polynomial: #.(#^2-#)&@*Range implements another common solution. (But it's also 17 bytes.) And we can implement the naive algorithm in 18 bytes: Tr@#^2-#.#&@*Range. Nov 5, 2018 at 15:46

# Java (JDK), 23 bytes

n->(3*n+2)*(n*n*n-n)/12


Try it online!

# MathGolf, 6 bytes

{î²ï*+


Try it online!

Calculates $$\\sum_{k=1}^n (k^2(k-1))\$$

### Explanation:

{       Loop (implicit) input times
î²     1-index of loop squared
*   Multiplied by
ï    The 0-index of the loop
+  And add to the running total


# 05AB1E, 8 bytes

ÝDOnsnO-


Explanation:

ÝDOnsnO-     //Full program
Ý            //Push [0..a] where a is implicit input
D           //Duplicate top of stack
On         //Push sum, then square it
s        //Swap top two elements of stack
nO      //Square each element, then push sum
-     //Difference (implicitly printed)


Try it online!

• LDnOsOn- was my first attempt too. Nov 7, 2018 at 4:23

## C, C++, 4640 37 bytes ( #define ), 5047 46 bytes ( function )

-1 byte thanks to Zacharý

-11 bytes thanks to ceilingcat

Macro version :

#define F(n)n*n*~n*~n/4+n*~n*(n-~n)/6


Function version :

int f(int n){return~n*n*n*~n/4+n*~n*(n-~n)/6;}


Thoses lines are based on thoses 2 formulas :

Sum of numbers between 1 and n = n*(n+1)/2
Sum of squares between 1 and n = n*(n+1)*(2n+1)/6

So the formula to get the answer is simply (n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6

And now to "optimize" the byte count, we break parenthesis and move stuff around, while testing it always gives the same result

(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6 => n*(n+1)/2*n*(n+1)/2 - n*(n+1)*(2n+1)/6 => n*(n+1)*n*(n+1)/4 - n*(n+1)*(2n+1)/6

Notice the pattern p = n*n+1 = n*n+n, so in the function, we declare another variable int p = n*n+n and it gives :

p*p/4 - p*(2n+1)/6

For p*(p/4-(2*n+1)/6) and so n*(n+1)*(n*(n+1)/4 - (2n+1)/6), it works half the time only, and I suspect integer division to be the cause ( f(3) giving 24 instead of 22, f(24) giving 85200 instead of 85100, so we can't factorize the macro's formula that way, even if mathematically it is the same.

Both the macro and function version are here because of macro substitution :

F(3) gives 3*3*(3+1)*(3+1)/4-3*(3+1)*(2*3+1)/6 = 22
F(5-2) gives 5-2*5-2*(5-2+1)*(5-2+1)/4-5-2*(5-2+1)*(2*5-2+1)/6 = -30

and mess up with the operator precedence. the function version does not have this problem

• You could fix up the problem with the macros at the cost of A LOT of bytes by replacing all the n with (n). Also, F(n) n=>F(n)n regardless. Nov 6, 2018 at 14:09
• It's possible to rearrange return p*p/4-p*(n-~n)/6 to return(p/4-(n-~n)/6)*p. Nov 10, 2018 at 19:41
• @Zacharý No, it gives me bad results sometimes like 24 instead of 22 for input "3", or 85200 instead of 85100 for input "24". I suspect integer division to be the cause of that Nov 10, 2018 at 21:38
• Ugh, always forget about that. Nov 10, 2018 at 21:39
• 34 bytes Try it online! Jul 15, 2021 at 16:43

# JavaScript (ES6), 22 bytes

n=>n*~-n*-~n*(n/4+1/6)


Try it online!

# Pyth, 7 bytes

sm**hdh


Try it online here.

Uses the formula in Neil's answer.

sm**hdhddQ   Implicit: Q=eval(input())
Trailing ddQ inferred
m       Q   Map [0-Q) as d, using:
hd         Increment d
*  hd       Multiply the above with another copy
*     d      Multiply the above by d
s            Sum, implicit print


# SNOBOL4 (CSNOBOL4), 70 69 bytes

 N =INPUT
I X =X + N ^ 3 - N ^ 2
N =GT(N) N - 1 :S(I)
OUTPUT =X
END


Try it online!

# Pari/GP, 21 bytes

n->(3*n+2)*(n^3-n)/12


Try it online!

# 05AB1E, 6 bytes

LnDƶαO


Try it online!

Explanation

L         # push range [1 ... input]
n        # square each
D       # duplicate
ƶ      # lift, multiply each by its 1-based index
α     # element-wise absolute difference
O    # sum


Some other versions at the same byte count:

L<ān*O
Ln.āPO
L¦nā*O

• You can use your bottom program and golf its ā* to ƶ for a 5-byter: L¦nƶO Oct 18, 2022 at 14:44

# R, 28 bytes

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


Try it online!

• sum(x<-1:scan())^2-sum(x^2) for -1 Nov 7, 2018 at 14:02

# Clojure, 58 bytes

(fn[s](-(Math/pow(reduce + s)2)(reduce +(map #(* % %)s))))


Try it online!

# Clojure, 55, 35 bytes

#(* %(+ 1 %)(- % 1)(+(* 3 %)2)1/12)


Try it online!

• Thanks for fixing that. And just a heads up regarding your last entry, (apply + is shorter than (reduce +. Nov 6, 2018 at 1:05
• Could you edit your permalink to run one of the test cases? As it is, I doesn't help people who don't know Clojure. Nov 6, 2018 at 1:47

# cQuents, 17 15 bytes

b$)^2-c$
;\$
;$$ Try it online! ## Explanation  b)^2-c First line : Implicit (output nth term in sequence) b) Each term in the sequence equals the second line at the current index ^2 squared -c minus the third line at the current index ; Second line - sum of integers up to n ;$$           Third line - sum of squares up to n


# MATLAB/Octave, 21 bytes

@(x)(x^3-x)*(x/4+1/6)


Anonymous function. We could save another 4 bytes if we assume x can be given as variable in workspace.
Implements $$\n(n−1)(n+1)(3n+2)/12\$$

One of my approaches was @(x)-sum([sum(1:x)*i,1:x].^2) which is few bytes longer but I found it interesting because It used imaginary unit to change the sign.
I also found out I can generate sum of squares by multiplying normal and transposed vector with (1:x)*(1:x)'. Might be useful for future challenges!

# Labyrinth, 20 bytes

?(:):):_3*(***_12/!@


Try it online!

Straightforward closed-form formula of $$\(x-1)x(x+1)(3x+2)/12\$$.

?      Take input [x]
(:):)  Decrement, dup, increment, dup, increment [x-1 x x+1]
:_3*(  Dup, 3 times, decrement [x-1 x x+1 3x+2]
***    Multiply four values
_12/   Divide by 12
!@     Print it and halt


# Labyrinth, 21 bytes

?
::(";;;!@
{  :
+**}


Try it online!

# Labyrinth, 22 bytes

   ?
:(::
}  "
**+{;!@


Try it online!

Two versions using a loop to evaluate $$\\sum_{i=1}^{x}{i^2(i-1)}\$$. Both versions test the loop exit with i-1 == 0, discard the top values ; as necessary, print the sum and exit.

?     Take input [x]; enter loop [sum i] with initial values of sum=0, i=x
::(   Dup, dup, decrement [sum i i i-1]
:}    Dup and move i-1 to aux. store [sum i i i-1 | i-1]
**+   Multiply top three values and add to sum [sum' | i-1]
{     Move i-1 back to the main stack

Loop exit test can be done anywhere in the last iteration
(i==1 or i==0), since that iteration does not affect the sum.


# ARM (Thumb), 18 bytes

.section .text
.global func
.thumb
// int func(int dummy, int x)
// returns sum(i*i*(i-1) for i in 1..x)
// r1 = i (x->1), r2 = i*i*(i-1), r0 = sum
func:
mov r0, #0       // 2000   int sum = 0;
mov r2, #0       // 2200   int prod = 0;
.loop:               //        do {
add r0, r0, r2   // 1880   sum += prod;
mov r2, r1       // 1c0a   prod = x;
mul r2, r1       // 434a   prod *= x;
sub r1, #1       // 3901   x -= 1;
mul r2, r1       // 434a   prod *= x;
bne .loop        // d1f9   } while (prod != 0);
bx lr            // 4770   return sum;


A function that takes the input integer via r1 and returns the value via r0.

Uses the iterative formula $$\\sum_{i=1}^{x}{i^2(i-1)}\$$, iterating backwards. The loop terminates when the value of $$\i^2(i-1)\$$ is 0.

For the purposes of writing test cases, the C-side function signature takes a dummy value for r0.

Test cases written in C:

#include <stdio.h>

int func(int dummy, int x);
int main(void) {
int dummy;
int inputs[] = {1, 2, 3, 10, 24, 100};
for(int i = 0; i < 6; ++i) {
int v = inputs[i];
printf("input = %d -> ans = %d\n", v, func(dummy, v));
}
return 0;
}


Build, run, objdump commands:

arm-linux-gnueabihf-gcc main_c.c func_c.S -static -o main_c
qemu-arm -L /usr/arm-linux-gnueabihf ./main_c
arm-linux-gnueabihf-objdump -d main_c | awk -v RS= '/^[[:xdigit:]]+ <(func|.loop)>/'


(The objdump + awk trick comes from this SO answer.)

# Vyxal, 8 bytes

ɾ∑²⁰ɾ²∑-


Try it Online!

literal solution, squares the sum and subtracts the sum of the squares.

# Factor + math.unicode, 32 bytes

[ [1,b] 3 dupn Σ sq -rot v. - ]


Try it online!

word   | data stack                                     | comment
-------+------------------------------------------------+--------------
| 10                                             | example input
[1,b]  | { 1 2 ... 10 }                                 |
3      | { 1 2 ... 10 } 3                               |
dupn   | { 1 2 ... 10 } { 1 2 ... 10 } { 1 2 ... 10 }   |
Σ      | { 1 2 ... 10 } { 1 2 ... 10 } 55               | sum
sq     | { 1 2 ... 10 } { 1 2 ... 10 } 3025             | square
-rot   | 3025 { 1 2 ... 10 } { 1 2 ... 10 }             |
v.     | 3025 385                                       | dot product
-      | 2640                                           | output