# Square pyramidal numbers

A000330 - OEIS

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.
• Fun observation from OEIS: This sequence contains exactly two perfect squares: f(1) == 1 * 1 (1), and f(24) == 70 * 70 (4900). Oct 17, 2017 at 16:31
• May we begin the sequence at f(1) = 1? Oct 18, 2017 at 6:10
• @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 Oct 18, 2017 at 9:44
• The f(0) = 0 requirement ruined a few of my solutions :( Oct 19, 2017 at 5:19

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

• This is very clever! Oct 17, 2017 at 16:00

# 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


(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'.

# MATL, 3 bytes

:Us


... or them?

Try it online!

### Explanation

:Us
:    % Implicit input n. Push range [1 2 ... n]
U   % Square, element-wise
s  % Sum of array. Implicit display


# 05AB1E, 3 bytes

ÝnO


Try it online!

Explanation

  O    # sum of
n     # squares of
Ý      # range [0 ... input]


# 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)

• Nicely done! :) I came up with ({<(({}))>{({})({}[()])}{}<({}[()])>}) for 38 Oct 17, 2017 at 16:20
• 34 bytes ;) Oct 17, 2017 at 19:00

# 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. 1: I came up with my solution before I looked at the answers here. So no plagiarism here.

• 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. Oct 17, 2017 at 19:02

# Jelly, 3 bytes

R²S


Try it online!

FGITW

# Explanation

R²S  Main Link
R    Generate Range
²   Square (each term)
S  Sum

• A longer alternative would be Ræ.R Oct 17, 2017 at 12:40

# Husk, 3 bytes

ṁ□ḣ


Try it online!

## 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: 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.

# Ohm v2, 3 bytes

#²Σ


Try it online!

Explanation

#    Range
²   Square
Σ  Sum


# Japt, 3 bytes

ô²x


Try it here.

-1 thanks to Shaggy.

Explanation:

ò²x
ô²  Map square on [0..input]
x Sum

• 3 bytes using the shortcut for p2. Oct 17, 2017 at 14:06
• @FelipeNardiBatista fixed Oct 18, 2017 at 11:21

# Brain-Flak, 46 bytes

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


Try it online!

• A little friendly competition :) Oct 17, 2017 at 13:29
• @Riley Ooh nice :) Oct 17, 2017 at 13:52
• 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) Oct 17, 2017 at 16:36

# CJam, 10 bytes

ri),{_*+}*


Try it online!

ri            e# Input integer n
,          e# Range [0 1 ... n]
{   }*    e# Fold (reduce)
_        e# Duplicate
*       e# Multiply

• How about ri),_.*:+ or ri),2f#:+? Oct 17, 2017 at 13:15
• @Martin Good idea! I think you should post it as a different answer Oct 17, 2017 at 13:25

# Wolfram Language (Mathematica), 14 bytes

Tr[Range@#^2]&


Try it online!

• #.#&@Range@#& saves a byte Oct 17, 2017 at 12:25
• #.#&@*Range . Oct 17, 2017 at 13:42

# Brachylog, 5 bytes

⟦^₂ᵐ+


Try it online!

### Explanation

⟦        Range
^₂ᵐ     Map square
+    Sum


# 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


# APL (Dyalog), 7 5 bytes

2 bytes saved thanks to @Mego

+.×⍨⍳


Try it online!

How?

⍳ - range

+.× - dot product

⍨ - with itself

• @Uriel my bad, i thought the ¨⍳ was necessary Oct 18, 2017 at 10:26

## R, 17 bytes

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


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

• (x=0:scan())%*%x is shorter by a byte, but I believe you need a cat to get output. Oct 17, 2017 at 14:21
• @Giuseppe I've just tried it and your code works without cat, it outputs a 1x1 matrix. Oct 19, 2017 at 16:30
• @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. Oct 19, 2017 at 16:33

## 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#


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

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


# 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


# 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!

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


Try it online!

# Excel, 19 bytes

=A1^3/3+A1^2/2+A1/6


# ><>, 1513 11 bytes

Saved 2 bytes thanks to Not a tree

0:n:l1-:*+!


Try it online!

Outputs the sequence indefinitely.

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

# 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

• Is there no square built in in Pyth? Oct 17, 2017 at 15:54
• Not as far as I know...
– Dave
Oct 17, 2017 at 16:01
• No there is no square built-in Pyth. Also 6 bytes Oct 17, 2017 at 16:15
• Oct 17, 2017 at 18:48
• Fixable with +1 byte to each answer, I'll edit once I get off of mobile.
– Dave
Oct 18, 2017 at 10:55

# J, 10 9 bytes

4%~3!2*>:


Try it online!

Saved 1 byte using an explicit formula, thanks to miles!

## J, 10 bytes

1#.]*:@-i.


J has a range function, but this gives us number from 0 to N-1. To remedy this, we can just take the argument and subtract the range from it, giving us a range from N to 1. This is done with ] -i.. The rest of the code simply square this list argument (*:@) and then sums it (1#.).

## Other contenders

11 bytes: 1#.*:@i.@>:

13 bytes: 1#.[:,@:*/~i.

• 4%~3!2*>: saves a byte Oct 19, 2017 at 11:45

# Thunno 2S, 2 bytes

R²


Attempt This Online!

#### Explanation

R²  # Implicit input
R   # Range of input
²  # Square each
# Sum the list
# Implicit output


# Nekomata, 3 bytes

R:∙


Attempt This Online!

R:∙
R     Range
:    Duplicate
∙   Dot product


Because there isn't a square built-in yet.