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

49 Answers 49

1
2
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\$

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\$
  • \$\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 '20 at 3:45
  • \$\begingroup\$ @Bubbler Thanks for the golf. (Glad that MIPS is getting popular!) \$\endgroup\$ – user96495 Aug 28 '20 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 '20 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\$

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!

\$\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\$
  • \$\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 '18 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 '18 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 '18 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\$
  • \$\begingroup\$ Is there an online interpreter for Axiom? \$\endgroup\$ – streetster Jun 17 '20 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\$
0
\$\begingroup\$

Whispers v2, 70 bytes

> 2
> Input
>> L³
>> L²
>> ∑ 1 2 3
>> ∑ 1 2 4
>> 5-6
>> Output 7

Try it online!

How it works

Implements the formula

$$\sum^n_{i=2}i^3 - \sum^n_{i=2}i^2$$

As Whispers is difficult to deal with when it comes to compound statements inside of , Each etc. statements, it's actually shorter to calculate two sums and take their difference than it is to calculate

$$\sum^n_{i=2}(i^3-i^2)$$

or any other single sum.

This has to be one of the easiest-to-read Whispers programs, aside from very trivial ones. We use the statement to calculate the two sums, which works by taking the starting bound as the first value, the end bound second and finally the function to sum through last. Both of the statements have the same bounds - \$2\$ and \$n\$ - so the only thing that differs is the function. For the first statement, we use the statement >> L³ (i.e. cube), and >> L² (square) for the second. This yields the sums \$\sum^n_{i=2}i^3\$ and \$\sum^n_{i=2}i^2\$. Finally, we take their difference and output it.

Whispers v3, 48 bytes

> 2
> Input
>>> L³-L²
>> ∑ 1 2 3
>> Output 4

With the introduction of pattern lines (starting with >>>) in version 3, compound statements in Whispers are much easier to deal with. Unfortunately, Whispers v3 is currently not available on TIO, so you'll have to use the interpreter in the Github repo.

This version takes advantage of pattern lines to shorten the code by only using one statement in the sum, rather than two separate sums. Other than that, it's fairly clear how it works, given the v2 program.

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

Haskell, 22 bytes

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

Pip, 21 bytes

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

My first self written pip answer!

Try it online!

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

05AB1E, 11 bytes

LDOnU€nOXs-

Try it online!

             # (implicit) push STDIN to stack
LD           # push [1, 2, 3, ..., top of stack] twice
  OnU        # store squared sum of all values in top of stack in variable X
     €       # for each in top of stack...
      n      # push top of stack squared
       O     # push sum of all values in top of stack
        Xs-  # push X - top of stack
             # (implicit) output top of stack to STDOUT
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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