# Square pyramidal numbers

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

- The bitwise complement of
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.}

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

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