Sum square difference

15

1

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.

  • The shortest answer wins.

Eduardo Hoefel

Posted 2018-11-04T18:58:33.017

Reputation: 587

A052149 – Shaggy – 2018-11-04T19:18:15.733

4This challenge needs a winning criterion (e.g. code golf) – dylnan – 2018-11-04T19:25:42.173

2

This is a subset of this question

– caird coinheringaahing – 2018-11-04T19:45:48.380

1Can the sequence be 0 indexed? i.e. the natural numbers up to n? – Jo King – 2018-11-04T23:49:19.820

5

Note that it's discouraged to post challenges directly taken from somewhere else.

– user202729 – 2018-11-05T05:53:45.530

3@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. – Jonathan Allan – 2018-11-05T08:33:21.943

#APL(NARS), 13 chars, 26 bytes

{+/⍵×⍵×⍵-1}∘⍳

use the formula Sumw=1..n test:

  g←{+/⍵×⍵×⍵-1}∘⍳
  g 0
0
  g 1
0
  g 2
4
  g 3
22
  g 10
2640
– RosLuP – 2018-11-05T10:27:24.277

@JonathanAllan: You need to spell my name correctly for me to receive a ping ;) Correct me if I'm wrong, but isn't this just the other challenge with a hardcoded to 1? In my opinion that is close enough to warrant a dupe, but if I'm alone with that opinion, feel free to vote to reopen. – Emigna – 2018-11-05T11:34:16.703

@Emigna wow, donnu how I manegad ttah, sorry :) porting an answer from there to here is easy, but probably not the golfiest, porting back seems non-trivial for the golfiest of solutions here; therefore I feel like this, while the same topic, justifies a separate question. (BTW I cannot "vote" to reopen, just hammer :( - I'll wait for other opinions) – Jonathan Allan – 2018-11-05T13:13:41.403

1@Emigna That makes sense, but in this case I think the challenge is simple enough that a small difference makes a big difference. The answers here are all about finding the most concise formula for the answer; almost none of the answers to the other question work that way. – Misha Lavrov – 2018-11-05T14:44:24.017

very closely related: https://codegolf.stackexchange.com/questions/83338

– Titus – 2018-11-06T06:15:18.863

Answers

10

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)

Jonathan Allan

Posted 2018-11-04T18:58:33.017

Reputation: 67 804

8

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

Jonathan Allan

Posted 2018-11-04T18:58:33.017

Reputation: 67 804

1You can shave a byte with n*~-n**2* or (n**3-n)*. – xnor – 2018-11-05T00:33:46.293

8

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

Bubbler

Posted 2018-11-04T18:58:33.017

Reputation: 16 616

For me 1⊥⍳×⍳×1-⍨⍳ is not a function ; I tried 1⊥⍳×⍳×1-⍨⍳10 and for me not compile... – RosLuP – 2018-11-05T13:32:07.130

1@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. – Bubbler – 2018-11-05T23:10:04.817

7

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.

Misha Lavrov

Posted 2018-11-04T18:58:33.017

Reputation: 4 846

Nice use of nCr! – Lynn – 2018-11-05T12:42:32.390

6

Brain-Flak, 74 72 68 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.

Post Rock Garf Hunter

Posted 2018-11-04T18:58:33.017

Reputation: 55 382

5

JavaScript, 20 bytes

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

Try it online

Shaggy

Posted 2018-11-04T18:58:33.017

Reputation: 24 623

1what deviltry is this – don bright – 2019-05-14T03:10:23.700

5

Charcoal, 12 10 bytes

IΣEN×ιX⊕ι²

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 \$.

   N        Input number
  E         Map over implicit range i.e. 0 .. n - 1
        ι   Current value
       ⊕    Incremented
         ²  Literal 2
      X     Power
     ι      Current value
    ×       Multiply
 Σ          Sum
I           Cast to string
            Implicitly print

Neil

Posted 2018-11-04T18:58:33.017

Reputation: 95 035

5

Perl 6, 22 bytes

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

Try it online!

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

Jo King

Posted 2018-11-04T18:58:33.017

Reputation: 38 234

4

Japt -x, 9 8 5 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

Shaggy

Posted 2018-11-04T18:58:33.017

Reputation: 24 623

3

APL(Dyalog), 17 bytes

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

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

Try it online!

Quintec

Posted 2018-11-04T18:58:33.017

Reputation: 2 801

Go tacit and combine the drops: +/¯1↓⍳×1⌽⍳×⍳ – Adám – 2018-11-05T15:50:48.943

3

APL (Dyalog), 16 bytes

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

Try it online!

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

Lynn

Posted 2018-11-04T18:58:33.017

Reputation: 55 648

(+/×⍨)1⊥×⍨ as per tip. – Adám – 2018-11-05T15:46:26.573

1A further byte could be saved by keeping the inside (×⍨1⊥⍳)-⍳+.×⍳ – user41805 – 2018-11-05T18:43:26.193

3

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.

LegionMammal978

Posted 2018-11-04T18:58:33.017

Reputation: 15 731

(3#+2)(#^3-#)/12& – alephalpha – 2018-11-05T04:43:45.297

@alephalpha Thanks! – LegionMammal978 – 2018-11-05T11:18:50.600

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. – Misha Lavrov – 2018-11-05T15:46:19.583

3

Java (JDK), 23 bytes

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

Try it online!

Olivier Grégoire

Posted 2018-11-04T18:58:33.017

Reputation: 10 647

3

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!

Cowabunghole

Posted 2018-11-04T18:58:33.017

Reputation: 1 590

LDnOsOn- was my first attempt too. – Magic Octopus Urn – 2018-11-07T04:23:51.150

3

dc, 16 bytes

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

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

Try it online!

Digital Trauma

Posted 2018-11-04T18:58:33.017

Reputation: 64 644

3

C, C++, 46 40 37 bytes ( #define ), 50 47 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

HatsuPointerKun

Posted 2018-11-04T18:58:33.017

Reputation: 1 891

1You 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. – Zacharý – 2018-11-06T14:09:46.937

It's possible to rearrange return p*p/4-p*(n-~n)/6 to return(p/4-(n-~n)/6)*p. – Zacharý – 2018-11-10T19:41:18.720

@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 – HatsuPointerKun – 2018-11-10T21:38:30.563

Ugh, always forget about that. – Zacharý – 2018-11-10T21:39:46.807

2

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

Stephen

Posted 2018-11-04T18:58:33.017

Reputation: 12 293

2

JavaScript (ES6), 22 bytes

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

Try it online!

Arnauld

Posted 2018-11-04T18:58:33.017

Reputation: 111 334

2

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!

Giuseppe

Posted 2018-11-04T18:58:33.017

Reputation: 21 077

2

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 

Sok

Posted 2018-11-04T18:58:33.017

Reputation: 5 592

2

Clojure, 58 bytes

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

Try it online!


Edit: I misunderstood the question

Clojure, 55, 35 bytes

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

Try it online!

TheGreatGeek

Posted 2018-11-04T18:58:33.017

Reputation: 111

1Thanks for fixing that. And just a heads up regarding your last entry, (apply + is shorter than (reduce +. – Carcigenicate – 2018-11-06T01:05:46.467

@Carcigenicate Thanks! – TheGreatGeek – 2018-11-06T01:09:32.843

1Could you edit your permalink to run one of the test cases? As it is, I doesn't help people who don't know Clojure. – Dennis – 2018-11-06T01:47:03.583

2

Pari/GP, 21 bytes

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

Try it online!

alephalpha

Posted 2018-11-04T18:58:33.017

Reputation: 23 988

2

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

Emigna

Posted 2018-11-04T18:58:33.017

Reputation: 50 798

2

R, 28 bytes

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

Try it online!

Sumner18

Posted 2018-11-04T18:58:33.017

Reputation: 1 334

3sum(x<-1:scan())^2-sum(x^2) for -1 – J.Doe – 2018-11-07T14:02:21.397

2

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

Jo King

Posted 2018-11-04T18:58:33.017

Reputation: 38 234

1

JAEL, 13 10 bytes

#&àĝ&oȦ

Try it online!

Explanation (generated automatically):

./jael --explain '#&àĝ&oȦ'
ORIGINAL CODE:  #&àĝ&oȦ

EXPANDING EXPLANATION:
à => `a
ĝ => ^g
Ȧ => .a!

EXPANDED CODE:  #&`a^g&o.a!

COMPLETED CODE: #&`a^g&o.a!,

#          ,            repeat (p1) times:
 &                              push number of iterations of this loop
  `                             push 1
   a                            push p1 + p2
    ^                           push 2
     g                          push p2 ^ p1
      &                         push number of iterations of this loop
       o                        push p1 * p2
        .                       push the value under the tape head
         a                      push p1 + p2
          !                     write p1 to the tapehead
            ␄           print machine state

Eduardo Hoefel

Posted 2018-11-04T18:58:33.017

Reputation: 587

1

APL(NARS), 13 chars, 26 bytes

{+/⍵×⍵×⍵-1}∘⍳

use the formula Sum'w=1..n'(ww(w-1)) possible i wrote the same some other wrote + or - as "1⊥⍳×⍳×⍳-1"; test:

  g←{+/⍵×⍵×⍵-1}∘⍳
  g 0
0
  g 1
0
  g 2
4
  g 3
22
  g 10
2640

RosLuP

Posted 2018-11-04T18:58:33.017

Reputation: 3 036

1

Stax, 4 bytes

╡⌠(♠

Run and debug it

For all positive k integers up to the input, add k^2 * (k-1).

recursive

Posted 2018-11-04T18:58:33.017

Reputation: 8 616

1

QBASIC, 45 44 bytes

Going pure-math saves 1 byte!

INPUT n
?n^2*(n+1)*(n+1)/4-n*(n+1)*(2*n+1)/6

Try THAT online!


Previous, loop-based answer

INPUT n
FOR q=1TO n
a=a+q^2
b=b+q
NEXT
?b^2-a

Try it online!

Note that the REPL is a bit more expanded because the interpreter fails otherwise.

steenbergh

Posted 2018-11-04T18:58:33.017

Reputation: 7 772

1

05AB1E, 6 bytes

LDOšnÆ

Try it online!

Explanation:

           # implicit input (example: 3)
L          # range ([1, 2, 3])
 DOš       # prepend the sum ([6, 1, 2, 3])
    n      # square each ([36, 1, 4, 9])
     Æ     # reduce by subtraction (22)
           # implicit output

Æ isn't useful often, but this is its time to shine. This beats the naïve LOnILnO- by two whole bytes.

Grimmy

Posted 2018-11-04T18:58:33.017

Reputation: 12 521

1

PowerShell, 73 39 bytes

1.."$args"|%{$r+=$_;$s+=$_*$_}
$r*$r-$s

Try it online!

-34 bytes thanks to @mazzy and his genius PowerShell-foo

KGlasier

Posted 2018-11-04T18:58:33.017

Reputation: 211

1

nice try. iex is a power tool in the Powershell. but it is often longer than the plus operator :) Try it online!

– mazzy – 2019-05-13T16:39:18.003

Damn @mazzy ... Thanks for the pro-tip! – KGlasier – 2019-05-13T16:42:20.810

formula as other solutions in this topic – mazzy – 2019-05-14T07:48:29.453

0

C#, 89 Bytes

int x=0,y=0;for(int i=1;i<=Int32.Parse(s[0]);i++){x+=i*i;y+=i;}Console.Write($"{y*y-x}");

ungolfed:

int x=0,y=0;
for(int i=1;i<=Int32.Parse(s[0]);i++){
x+=i*i;
y+=i;
}
Console.Write($"{y*y-x}");

Try it online!

user51497

Posted 2018-11-04T18:58:33.017

Reputation: 113

You can save 31 bytes if you use a function to read in and return ints, as well as make some changes with the for loop call. Try it online!

– Meerkat – 2018-11-05T19:27:35.770

@Meerkat Is one allowed to put the Output code in the footer? Then I get to 57 bytes

– user51497 – 2018-11-05T21:01:57.733

Output is supposed to be in the body. With the function call, this is what the return essentially does, which is why it's included in the body. – Meerkat – 2018-11-05T21:28:23.093

0

Axiom, 39 bytes

f(n)==reduce(+,[x^3-x^2 for x in 1..n])

test:

-> [[x,f x]for x in [1,2,3,10]]
     [[1,0],[2,4],[3,22],[10,2640]]

RosLuP

Posted 2018-11-04T18:58:33.017

Reputation: 3 036

0

Clojure, 91 bytes

(fn s[n](let[u #(apply + %)q #(Math/pow % 2)m(range 1(inc n))](-(q(u m))(u(map #(q %)m)))))

The naive, literal approach. See below:

(defn sum-sq-diff [n]
    (let [; Shortcut functions to save bytes
          sum #(apply + %)
          square #(Math/pow % 2)
          nums (range 1 (inc n))

          ss1 (sum (map #(square %) nums))
          ss2 (square (sum nums))]

      (- ss2 ss1)))

(mapv sum-sq-diff [1 2 3 10 24 100])
=> [0.0 4.0 22.0 2640.0 85100.0 2.516415E7]

Try it online!

Carcigenicate

Posted 2018-11-04T18:58:33.017

Reputation: 3 295

0

Ruby, 24 bytes

->n{(n+n+3*n*=n)*~-n/12}

Try it online!

G B

Posted 2018-11-04T18:58:33.017

Reputation: 11 099

0

Python 3, 72 bytes

x=[i+1for i in range(int(input()))]
print(sum(x)**2-sum(i**2for i in x))

Try it online!

glietz

Posted 2018-11-04T18:58:33.017

Reputation: 101

0

F# (Mono), 57 41 bytes

let f x=Seq.sumBy(fun y->y*y*(y-1))[1..x]

Try it online!

dana

Posted 2018-11-04T18:58:33.017

Reputation: 2 541

0

PHP, 37 bytes

while($i<$argn)$s+=$i++*$i*$i;echo$s;

Try it online!

Standalone program input number via STDIN. Example:

$ echo 10|php -nF ssd.php
2640
$ echo 100|php -nF ssd.php
25164150

640KB

Posted 2018-11-04T18:58:33.017

Reputation: 7 149

0

Perl 6, 22 bytes

{($_³-$_)*($_/4+⅙)}

Try it online!

bb94

Posted 2018-11-04T18:58:33.017

Reputation: 1 831