28
\$\begingroup\$

A000330 - OEIS

Task

Your task is simple, generate a sequence that, given index i, the value on that position is the sum of squares from 0 upto i where i >= 0.

Example:

Input: 0
Output: 0           (0^2)

Input: 4
Output: 30          (0^2 + 1^2 + 2^2 + 3^2 + 4^2)

Input: 5
Output: 55          (0^2 + 1^2 + 2^2 + 3^2 + 4^2 + 5^2)

Specification:

  • You may take no input and output the sequence indefinitely;
  • You may take input N and output the Nth element of the sequence;
  • You may take input N and output the first N elements of the sequence.
\$\endgroup\$
  • 2
    \$\begingroup\$ Fun observation from OEIS: This sequence contains exactly two perfect squares: f(1) == 1 * 1 (1), and f(24) == 70 * 70 (4900). \$\endgroup\$ – DJMcMayhem Oct 17 '17 at 16:31
  • \$\begingroup\$ May we begin the sequence at f(1) = 1? \$\endgroup\$ – Emigna Oct 18 '17 at 6:10
  • \$\begingroup\$ @Emigna sorry but no, you need to start from f(0) = 0. i've pointed out that to the few answers that failed that requirement \$\endgroup\$ – Felipe Nardi Batista Oct 18 '17 at 9:44
  • \$\begingroup\$ The f(0) = 0 requirement ruined a few of my solutions :( \$\endgroup\$ – ATaco Oct 19 '17 at 5:19

72 Answers 72

4
\$\begingroup\$

Jelly, 3 bytes

R²S

Try it online!

FGITW

Explanation

R²S  Main Link
R    Generate Range
 ²   Square (each term)
  S  Sum
\$\endgroup\$
  • \$\begingroup\$ A longer alternative would be Ræ.R \$\endgroup\$ – Mr. Xcoder Oct 17 '17 at 12:40
22
\$\begingroup\$

Python 2, 22 bytes

lambda n:n*~n*~(n*2)/6

Try it online!

This uses the closed-form formula n * (n+1) * (2*n+1) / 6. The code performs the following operations:

  • Multiplies n by (n*):

    • The bitwise complement of n (~n), which essentially means -1-n.
    • And by the bitwise complement of 2n (*~(n*2)), which means -1-2n.
  • Divides by 6 (/6).

Python 2, 27 bytes

f=lambda n:n and f(n-1)+n*n

Try it online!

Saved 1 byte thanks to Rod and 1 thanks to G B.

\$\endgroup\$
  • 1
    \$\begingroup\$ This is very clever! \$\endgroup\$ – Skyler Oct 17 '17 at 16:00
14
\$\begingroup\$

MATL, 3 bytes

:Us

... or them?

Try it online!

Explanation

:    % Implicit input n. Push range [1 2 ... n]
U    % Square, element-wise
s    % Sum of array. Implicit display
\$\endgroup\$
14
\$\begingroup\$

JavaScript (ES6), 16 bytes

n=>n*(n+++n)*n/6

Demo

let f =

n=>n*(n+++n)*n/6

for(n = 0; n < 10; n++) {
  console.log('a(' + n + ') = ' + f(n))
}

How?

The expression n+++n is parsed as n++ + n (1). Not that it really matters because n + ++n would also work in this case.

Therefore:

n*(n+++n)*n/6 =
n * (n + (n + 1)) * (n + 1) / 6 =
n * (2 * n + 1) * (n + 1) / 6

which evaluates to sum(k=0...n)(k²).


(1) This can be verified by doing n='2';console.log(n+++n) which gives the integer 5, whereas n + ++n would give the string '23'.

\$\endgroup\$
6
\$\begingroup\$

05AB1E, 3 bytes

ÝnO

Try it online!

Explanation

  O    # sum of
 n     # squares of
Ý      # range [0 ... input]
\$\endgroup\$
6
\$\begingroup\$

Brain-Flak, 36 bytes

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

Try it online!

# Main algorithm
(                                  )  # Push the sum of:
                {({})({}[()])}{}      #   The square of:
 {                              }     #     0 to i 

# Stuff for the loop
  <(({}[()])())>                      # Push i-1, i without counting it in the sum
                                 {}   # Pop the counter (0)
\$\endgroup\$
  • \$\begingroup\$ Nicely done! :) I came up with ({<(({}))>{({})({}[()])}{}<({}[()])>}) for 38 \$\endgroup\$ – DJMcMayhem Oct 17 '17 at 16:20
  • \$\begingroup\$ 34 bytes ;) \$\endgroup\$ – Sriotchilism O'Zaic Oct 17 '17 at 19:00
6
\$\begingroup\$

Brain-Flak, 34 bytes

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

Try it online!

How does it work?

Initially I had the same idea as Riley1 but it felt wrong to use a zeroer. I then realized that

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

Calculates n2 - n.

Why? Well we know

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

Calculates n2 and loops n times. That means if we switch the order of the two pushes we go from increasing the sum by n + (n-1) each time to increasing the sum by (n-1) + (n-1) each time. This will decrease the result by one per loop, thus making our result n2 - n. At the top level this -n cancels with the n generated by the push that we were zeroing alleviating the need for a zeroer and saving us two bytes.

Brain-Flak, 36 bytes

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

Try it online!

Here is another solution, its not as golfy but it's pretty strange so I thought I would leave it as a challenge to figure out how it works.

If you are not into Brain-Flak but you still want the challenge here it is as a summation.

Picture


1: I came up with my solution before I looked at the answers here. So no plagiarism here.

\$\endgroup\$
  • \$\begingroup\$ I knew there had to be a way to do this, and I had a feeling you would be the one to figure out the math for it. \$\endgroup\$ – Riley Oct 17 '17 at 19:02
4
\$\begingroup\$

Husk, 3 bytes

ṁ□ḣ

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Ohm v2, 3 bytes

#²Σ

Try it online!

Explanation

#    Range
 ²   Square
  Σ  Sum
\$\endgroup\$
3
\$\begingroup\$

Japt, 3 bytes

ô²x

Try it here.

-1 thanks to Shaggy.

Explanation:

ò²x 
ô²  Map square on [0..input]
  x Sum
\$\endgroup\$
  • \$\begingroup\$ 3 bytes using the shortcut for p2. \$\endgroup\$ – Shaggy Oct 17 '17 at 14:06
  • \$\begingroup\$ @FelipeNardiBatista fixed \$\endgroup\$ – Erik the Outgolfer Oct 18 '17 at 11:21
2
\$\begingroup\$

Brain-Flak, 46 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ A little friendly competition :) \$\endgroup\$ – Riley Oct 17 '17 at 13:29
  • \$\begingroup\$ @Riley Ooh nice :) \$\endgroup\$ – HyperNeutrino Oct 17 '17 at 13:52
  • \$\begingroup\$ Rather than pushing the square onto the alternate stack, you can sum it directly by evaluating and not pushing it, then pushing the whole loop instead. This changes your second half to ({{({})({}[()])}{}}{}), and saves you 10 bytes. (If that doesn't make sense, ping me in the third stack) \$\endgroup\$ – DJMcMayhem Oct 17 '17 at 16:36
2
\$\begingroup\$

CJam, 10 bytes

ri),{_*+}*

Try it online!

ri            e# Input integer n
  )           e# Add 1
   ,          e# Range [0 1 ... n]
    {   }*    e# Fold (reduce)
     _        e# Duplicate
      *       e# Multiply
       +      e# Add
\$\endgroup\$
  • \$\begingroup\$ How about ri),_.*:+ or ri),2f#:+? \$\endgroup\$ – Martin Ender Oct 17 '17 at 13:15
  • \$\begingroup\$ @Martin Good idea! I think you should post it as a different answer \$\endgroup\$ – Luis Mendo Oct 17 '17 at 13:25
2
\$\begingroup\$

Wolfram Language (Mathematica), 14 bytes

Tr[Range@#^2]&

Try it online!

\$\endgroup\$
  • 4
    \$\begingroup\$ #.#&@Range@#& saves a byte \$\endgroup\$ – miles Oct 17 '17 at 12:25
  • 4
    \$\begingroup\$ #.#&@*Range . \$\endgroup\$ – alephalpha Oct 17 '17 at 13:42
2
\$\begingroup\$

Actually, 3 bytes

R;*

Try it online!

Takes N as input, and outputs the Nth element in the sequence.

Explanation:

R;*
R    range(1, N+1) ([1, 2, ..., N])
 ;*  dot product with self
\$\endgroup\$
2
\$\begingroup\$

APL (Dyalog), 7 5 bytes

2 bytes saved thanks to @Mego

+.×⍨⍳

Try it online!

How?

- range

+.× - dot product

- with itself

\$\endgroup\$
  • \$\begingroup\$ @Uriel my bad, i thought the ¨⍳ was necessary \$\endgroup\$ – Felipe Nardi Batista Oct 18 '17 at 10:26
2
\$\begingroup\$

R, 17 bytes

sum((0:scan())^2)

Pretty straightforward, it takes advantage from the fact that ^ (exponentiation) is vectorized in R.

\$\endgroup\$
  • 1
    \$\begingroup\$ (x=0:scan())%*%x is shorter by a byte, but I believe you need a cat to get output. \$\endgroup\$ – Giuseppe Oct 17 '17 at 14:21
  • \$\begingroup\$ @Giuseppe I've just tried it and your code works without cat, it outputs a 1x1 matrix. \$\endgroup\$ – Rui Barradas Oct 19 '17 at 16:30
  • \$\begingroup\$ @RuiBarradas Current meta consensus is that cat is necessary for this to qualify as a full program. If you wish to change that, answer this question and get some traction among the other R people on the site. \$\endgroup\$ – Giuseppe Oct 19 '17 at 16:33
2
\$\begingroup\$

CJam, 9 bytes

ri),_.*:+

Try it online!

Explanation

ri        e# Read input and convert to integer N.
  ),      e# Get range [0 1 2 ... N].
    _     e# Duplicate.
     .*   e# Pairwise products, giving [0 1 4 ... N^2].
       :+ e# Sum.

Alternatively:

ri),2f#:+

This squares each element by mapping 2# instead of using pairwise products. And just for fun another alternative which gets inaccurate for large inputs because it uses floating-point arithmetic:

ri),:mh2#
\$\endgroup\$
2
\$\begingroup\$

Julia, 16 14 bytes

2 bytes saved thanks to @MartinEnder

!n=(x=1:n)⋅x

Try it online!

How?

(x=1:n) creates a range of 1 to n and assign to x, dot product with x.

\$\endgroup\$
2
\$\begingroup\$

Labyrinth, 11 bytes

:!\
+ :
*:#

Try it online!

Prints the sequence indefinitely.

Explanation

The instruction pointer just keeps running around the square of code over and over:

:!\    Duplicate the last result (initially zero), print it and a linefeed.
:      Duplicate the result again, which increases the stack depth.
#      Push the stack depth (used as a counter variable).
:*     Square it.
+      Add it to the running total.
\$\endgroup\$
2
\$\begingroup\$

Cubix, 15 bytes

Iu):^\+*p*6u@O,

Try it online!

My code is a bit sad ):

Computes n*(n+1)*(2n+1)/6

    I u
    ) :
^ \ + * p * 6 u
@ O , . . . . .
    . .
    . .

^Iu : read in input, u-turn
    : stack  n
:)\ : dup, increment, go right..oh, hey, it cheered up!
    : stack: n, n+1
+   : sum
    : stack: n, n+1, 2*n+1
*   : multiply
    : stack: n, n+1, 2*n+1, (n+1)*(2*n+1)
p   : move bottom of stack to top
    : stack: n+1, 2*n+1, (n+1)*(2*n+1), n
*   : multiply
6   : push 6
u   : right u-turn
,   : divide
O   : output
@   : terminate

\$\endgroup\$
2
\$\begingroup\$

Befunge, 16 bytes

&::2*1+*\1+*6/.@

Using the closed-form formula n*(n+1)*(2n+1)/6.

Try it online!

Befunge, 38 bytes

v>::*\1-:v0+_$.@
&^ <     _\:^
>:#^_.@

Using a loop.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Haskell, 20 bytes

f 0=0
f n=n*n+f(n-1)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Excel, 19 bytes

=A1^3/3+A1^2/2+A1/6
\$\endgroup\$
2
\$\begingroup\$

Hexagony, 23 bytes

?'+)=:!@/*"*'6/{=+'+}/{

Try it online!

Explanation

Unfolded:

   ? ' + )
  = : ! @ /
 * " * ' 6 /
{ = + ' + } /
 { . . . . .
  . . . . .
   . . . .

This is really just a linear program with the / used for some redirection. The linear code is:

?'+){=+'+}*"*'6{=:!@

Which computes n (n+1) (2n+1) / 6. It uses the following memory edges:

enter image description here

Where the memory point (MP) starts on the edge labelled n, pointing north.

?   Read input into edge labelled 'n'.
'   Move MP backwards onto edge labelled 'n+1'.
+   Copy 'n' into 'n+1'.
)   Increment the value (so that it actually stores the value n+1).
{=  Move MP forwards onto edge labelled 'temp' and turn around to face
    edges 'n' and 'n+1'.
+   Add 'n' and 'n+1' into edge 'temp', so that it stores the value 2n+1.
'   Move MP backwards onto edge labelled '2n+1'.
+   Copy the value 2n+1 into this edge.
}   Move MP forwards onto 'temp' again.
*   Multiply 'n' and 'n+1' into edge 'temp', so that it stores the value
    n(n+1).
"   Move MP backwards onto edge labelled 'product'.
*   Multiply 'temp' and '2n+1' into edge 'product', so that it stores the
    value n(n+1)(2n+1).
'   Move MP backwards onto edge labelled '6'.
6   Store an actual 6 there.
{=  Move MP forwards onto edge labelled 'result' and turn around, so that
    the MP faces edges 'product' and '6'.
:   Divide 'product' by '6' into 'result', so that it stores the value
    n(n+1)(2n+1)/6, i.e. the actual result.
!   Print the result.
@   Terminate the program.

In theory it might be possible to fit this program into side-length 3, because the / aren't needed for the computation, the : can be reused to terminate the program, and some of the '"=+*{ might be reusable as well, bringing the number of required commands below 19 (the maximum for side-length 3). I doubt it's possible to find such a solution by hand though, if one exists at all.

\$\endgroup\$
2
\$\begingroup\$

><>, 15 13 11 bytes

Saved 2 bytes thanks to Not a tree

0:n:l1-:*+!

Try it online!

Outputs the sequence indefinitely.

\$\endgroup\$
  • 1
    \$\begingroup\$ 14 bytes (12+2 for -v flag): ::1+:}+**6,n (Try it online!) \$\endgroup\$ – Not a tree Oct 18 '17 at 1:43
  • 1
    \$\begingroup\$ Or 11 bytes (prints forever, starting at N=1): Try it online! \$\endgroup\$ – Not a tree Oct 18 '17 at 2:00
  • \$\begingroup\$ @Notatree: Very nice idea using l. Checking with OP if it is okay to start at 1. \$\endgroup\$ – Emigna Oct 18 '17 at 6:28
  • \$\begingroup\$ @Notatree: Unfortunately we aren't allowed to start at 1, but it still saves 2 bytes. Thanks! \$\endgroup\$ – Emigna Oct 18 '17 at 9:52
  • 1
    \$\begingroup\$ (I should mention that I got the l idea from Martin Ender's Labyrinth answer.) \$\endgroup\$ – Not a tree Oct 18 '17 at 14:59
2
\$\begingroup\$

Pyth, 7 5 bytes thanks to Steven H

s^R2h

Explanation:

s^R2h       Full program - inputs from stdin and outputs to stdout
s           output the sum of
    h       range(input), with
 ^R2         each element squared

My first solution

sm*ddUh

Try it online!

Explanation:

sm*ddUh    Full program - inputs from stdin and outputs to stdout
s          sum of
 m   Uh    each d in range(input)
  *dd      squared
\$\endgroup\$
  • \$\begingroup\$ Is there no square built in in Pyth? \$\endgroup\$ – caird coinheringaahing Oct 17 '17 at 15:54
  • \$\begingroup\$ Not as far as I know... \$\endgroup\$ – Dave Oct 17 '17 at 16:01
  • \$\begingroup\$ No there is no square built-in Pyth. Also 6 bytes \$\endgroup\$ – Mr. Xcoder Oct 17 '17 at 16:15
  • 1
    \$\begingroup\$ 5 bytes. \$\endgroup\$ – Steven H. Oct 17 '17 at 18:48
  • \$\begingroup\$ Fixable with +1 byte to each answer, I'll edit once I get off of mobile. \$\endgroup\$ – Dave Oct 18 '17 at 10:55
1
\$\begingroup\$

Neim, 3 bytes

𝐈ᛦ𝐬

This could've been a challenge to show off Neim's polygonal number builtins, but apparently not.

Try it online!

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

Oasis, 4 bytes

nk+0

Try it online!

Explanation

   0      # a(0) = 0
nk+       # a(n) = a(n-1)+n^2
\$\endgroup\$
1
\$\begingroup\$

Brachylog, 5 bytes

⟦^₂ᵐ+

Try it online!

Explanation

⟦        Range
 ^₂ᵐ     Map square
    +    Sum
\$\endgroup\$
1
\$\begingroup\$

Gaia, 3 bytes

s¦Σ

Try it online!

\$\endgroup\$

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.