29
\$\begingroup\$

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.

\$\endgroup\$
11
  • 4
    \$\begingroup\$ This challenge needs a winning criterion (e.g. code golf) \$\endgroup\$
    – dylnan
    Nov 4, 2018 at 19:25
  • 2
    \$\begingroup\$ This is a subset of this question \$\endgroup\$ Nov 4, 2018 at 19:45
  • 1
    \$\begingroup\$ Can the sequence be 0 indexed? i.e. the natural numbers up to n? \$\endgroup\$
    – Jo King
    Nov 4, 2018 at 23:49
  • 5
    \$\begingroup\$ Note that it's discouraged to post challenges directly taken from somewhere else. \$\endgroup\$
    – DELETE_ME
    Nov 5, 2018 at 5:53
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ Nov 5, 2018 at 8:33

63 Answers 63

2
\$\begingroup\$

Fig, \$9\log_{256}(96)\approx\$ 7.408 bytes

a
R@-mQJS

Try it online!

Port of 05AB1E. Literal solution is 2 chars longer.

a
R@-mQJS
-------
a       # Range [1, n]
------- # Use ^ as the input to the next line:
     JS # Prepend the sum to the list
   mQ   # Square each
R@      # Reduce by
  -     # Subtraction
\$\endgroup\$
2
\$\begingroup\$

Excel, 21 bytes

=(A1^3-A1)*(A1/4+1/6)

This is the heartless Excel version of the formula figured out by others. There is also the 33 byte solution that feels a little more Excel-y:

=LET(n,SEQUENCE(A1),SUM(n^3-n^2))

... and the 38 byte solution that looks the most like the original formulas in the question:

=LET(n,SEQUENCE(A1),SUM(n)^2-SUMSQ(n))
\$\endgroup\$
2
\$\begingroup\$

Husk, 11 8 bytes

-ṁ□ḣ¹□Σḣ

Try it online!

Explanation

-ṁ□ḣ¹□Σḣ
-              Subtract
 ṁ□ḣ¹          The sum of the first n squares
     □         From the square of
      Σḣ       The sum from 1 to n

First time code golfing so this solution probably can be improved.

Thanks to Dominic van Essen for the -3 bytes.

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf! Nice answer in a great language! One golf you might make is to use ¹ to implicitly add the fina ```⁰```` like this... \$\endgroup\$ Oct 18, 2022 at 20:39
  • \$\begingroup\$ Also, don't forget , which can save a bit compared to …1: try it or, equivalently this... \$\endgroup\$ Oct 18, 2022 at 20:43
2
\$\begingroup\$

Julia 1.0, 20 bytes

Using the same formula as bigyihsuan:

~n=(n^3-n)*(3n+2)/12

Try it online!


Naive approach (34 bytes):
~n=(a=[1:n...];sum(a)^2-sum(a.^2))

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ another naive approach almost matching (2 bytes longer) the formula ~n=sum((a=0:n;))^2-a'a \$\endgroup\$
    – amelies
    Oct 20, 2022 at 12:57
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Stax, 4 bytes

╡⌠(♠

Run and debug it

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

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
0
1
\$\begingroup\$

PowerShell, 73 39 bytes

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

Try it online!

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ nice try. iex is a power tool in the Powershell. but it is often longer than the plus operator :) Try it online! \$\endgroup\$
    – mazzy
    May 13, 2019 at 16:39
  • \$\begingroup\$ Damn @mazzy ... Thanks for the pro-tip! \$\endgroup\$
    – KGlasier
    May 13, 2019 at 16:42
  • \$\begingroup\$ formula as other solutions in this topic \$\endgroup\$
    – mazzy
    May 14, 2019 at 7:48
1
\$\begingroup\$

International Phonetic Esoteric Language, 21 bytes

ɪbwbbbffʍz3ʍf2sf{C}vo

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

Explanation:

ɪ       (input)
bw      (store n)
bbbffʍz (n^3-n)
3ʍf2s   (3n+2)
f       (multiply)
{C}v    (/12)
o       (print)

Testing against examples:

$ for i in 1 2 3 10 24 100; do echo {$i} | src/interpreter.py 'ɪbwbbbffʍz3ʍf2sf{C}vo'; done
0.0
4.0
22.0
2640.0
85100.0
25164150.0
\$\endgroup\$
1
\$\begingroup\$

Arn, 9 bytes

└V0¯„○aÌ$

Try it!

Explained

Unpacked: +{^3-^2}\~.

Performs \$\large\sum_{k=1}^{n}{(k^3-k^2)}\$ where n is the input

          \       Fold with
+                 Addition
  {               After mapping with this block
        _         Implied variable (implicit index of block).
      ^           To the power of
        3         Literal three
    -             Minus
        _
      ^
        2         Literal two
  }               End block
            ~     1-range to
              _   Initialized to STDIN; implied
\$\endgroup\$
1
\$\begingroup\$

Haskell, 22 bytes

f n=(3*n+2)*(n^3-n)/12
\$\endgroup\$
1
\$\begingroup\$

Pip, 21 bytes

($+\,a)**2-$+(\,a)**2

My first self written pip answer!

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Assembly (MIPS, SPIM), 142 114 bytes, 6 * 12 10 = 72 60 assembled bytes

Saved 2 instructions (12 bytes) from @Bubbler's golf.

main:li$v0,5
syscall
li$a0,0
l:mul$t0,$v0,$v0
sub$v0,$v0,1
mul$t0,$t0,$v0
add$a0,$a0,$t0
bgtz$v0,l
li$v0,1
syscall

Try it online!

Explanation

main:
    li $v0, 5              # Set syscall value 5
    syscall                # Syscall, v0 = input integer

    li $a0, 0              # a0 = 0

    loop:                  # Main loop (v0 is the counter):
        mul $t0, $v0, $v0  #     t0 = v0 * v0
        sub $v0, $v0, 1    #     v0 = v0 - 1
        mul $t0, $t0, $v0  #     t0 = t0 * v0
        add $a0, $a0, $t0  #     a0 = a0 + t0

        bgtz $v0, loop     #     if v0 > 0, jump to loop

    li $v0, 1              # Syscall value 1
    syscall                # Syscall (Output value of a0 as integer)
\$\endgroup\$
3
  • \$\begingroup\$ Since the square of sum is the sum of cubes, you can optimize it to "iterate $v0 from n to 1, summing the values of $v0 * $v0 * ($v0 - 1)". Like this. \$\endgroup\$
    – Bubbler
    Aug 28, 2020 at 3:45
  • \$\begingroup\$ @Bubbler Thanks for the golf. (Glad that MIPS is getting popular!) \$\endgroup\$
    – user96495
    Aug 28, 2020 at 4:13
  • 1
    \$\begingroup\$ You can cut one instruction with bgtz, which is the opposite condition of beqz here. TIO \$\endgroup\$
    – Bubbler
    Aug 28, 2020 at 7:04
1
\$\begingroup\$

Flurry -nii, 32 bytes

{}{{}[<><<>()>]<([])[][]>}[<>()]

Try it online!

Iterates through k=0 .. n-1 using the stack height, adding k(k+1)^2 each iteration.

How it works

main = n add-next-term 0

// Initial height is 0
// Increase the height at (push height), so subsequent `height` calls give k+1
add-next-term = \x. x succ <(push height) height height>
= \x. x + k * (k+1) * (k+1)
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 59 48 47 bytes

n=>(a=(x,b)=>x&&x*(b||x)+a(--x,b))(n,1)**2-a(n)

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ 48 bytes \$\endgroup\$
    – Shaggy
    Jul 7, 2021 at 11:55
  • \$\begingroup\$ yeah i probably might ditch the reading from input thing lol, i never knew ** existed \$\endgroup\$
    – mekb
    Jul 7, 2021 at 11:57
  • \$\begingroup\$ 47 bytes \$\endgroup\$
    – Shaggy
    Jul 7, 2021 at 13:13
1
\$\begingroup\$

C (gcc), 29 bytes

f(n){n=(3*n+2)*(n*n*n-n)/12;}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

J, 15 bytes

(+/@:**:@>:)@i.

Uses the form \$\sum_{i=0}^{n-1}((i+1)^2\cdot i)\$

Attempt This Online!

(+/@:**:@>:)@i.
             i. NB. range 0..n-1
            @   NB. atop f (g x)
(          )    NB. monadic hook, y f (g y)
      *:@>:     NB. increment then square
 +/@:*          NB. multiply square with each i then sum the result
                NB. u@:v where v is dyadic and u is always monadic,
                NB. like atop except u will execute once on the entire result
\$\endgroup\$
1
\$\begingroup\$

Pip, 15 13 11 bytes

SQ_*D_MS\,a

Try It Online!

Explanation

Adapted from one of the formulas in Engineer Toast's Excel answer:

$$ \sum_{i=1}^{n} i^3-i^2 $$

which is equivalent to

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

SQ_*D_MS\,a
          a  Command-line argument
        \,   Inclusive range from 1
      MS     Map this function to each and sum the results:
SQ_            The argument squared
   *           Times
    D_         The argument decremented

Original 15-byte solution that implements the description directly:

\,:aSQ$+a-$+SQa

Try It Online!

\$\endgroup\$
1
\$\begingroup\$

Vyxal, 7 bytes

ɾ:∑p²ƒ-

Try it Online!

A port of Fig which is a port of 05ab1e

Explained

ɾ:∑p²ƒ-
ɾ:∑p     # prepend the sum of the range [1, n] to the range [1, n]
   ²ƒ-  # square everything and reduce by subtraction
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
3
  • \$\begingroup\$ 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! \$\endgroup\$
    – Meerkat
    Nov 5, 2018 at 19:27
  • \$\begingroup\$ @Meerkat Is one allowed to put the Output code in the footer? Then I get to 57 bytes \$\endgroup\$
    – some_user
    Nov 5, 2018 at 21:01
  • \$\begingroup\$ 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. \$\endgroup\$
    – Meerkat
    Nov 5, 2018 at 21:28
0
\$\begingroup\$

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]]
\$\endgroup\$
1
  • \$\begingroup\$ Is there an online interpreter for Axiom? \$\endgroup\$
    – mkst
    Jun 17, 2020 at 9:56
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

Ruby, 24 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

F# (Mono), 57 41 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Perl 6, 22 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

PHP, 37 bytes

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

Try it online!

Standalone program input number via STDIN.

\$\endgroup\$
0
\$\begingroup\$

Keg, 15 bytes

&⑻Ï⑷²⑸⅀⑻:⑨*½²$-

Try it online!

Calculates the sum of squares then the square of the sum.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.