Square pyramidal numbers

28

1

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.

Felipe Nardi Batista

Posted 2017-10-17T11:53:55.173

Reputation: 2 345

2Fun observation from OEIS: This sequence contains exactly two perfect squares: f(1) == 1 * 1 (1), and f(24) == 70 * 70 (4900). – James – 2017-10-17T16:31:10.910

May we begin the sequence at f(1) = 1? – Emigna – 2017-10-18T06:10:34.810

@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 – Felipe Nardi Batista – 2017-10-18T09:44:20.383

The f(0) = 0 requirement ruined a few of my solutions :( – ATaco – 2017-10-19T05:19:11.237

Answers

4

Jelly, 3 bytes

R²S

Try it online!

FGITW

Explanation

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

HyperNeutrino

Posted 2017-10-17T11:53:55.173

Reputation: 26 575

A longer alternative would be Ræ.R – Mr. Xcoder – 2017-10-17T12:40:49.210

22

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.

Mr. Xcoder

Posted 2017-10-17T11:53:55.173

Reputation: 39 774

1This is very clever! – Skyler – 2017-10-17T16:00:25.810

14

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

Luis Mendo

Posted 2017-10-17T11:53:55.173

Reputation: 87 464

14

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

Arnauld

Posted 2017-10-17T11:53:55.173

Reputation: 111 334

6

05AB1E, 3 bytes

ÝnO

Try it online!

Explanation

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

Emigna

Posted 2017-10-17T11:53:55.173

Reputation: 50 798

6

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)

Riley

Posted 2017-10-17T11:53:55.173

Reputation: 11 345

Nicely done! :) I came up with ({<(({}))>{({})({}[()])}{}<({}[()])>}) for 38 – James – 2017-10-17T16:20:03.930

34 bytes ;) – Post Rock Garf Hunter – 2017-10-17T19:00:05.587

6

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.

Post Rock Garf Hunter

Posted 2017-10-17T11:53:55.173

Reputation: 55 382

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. – Riley – 2017-10-17T19:02:21.120

4

Husk, 3 bytes

ṁ□ḣ

Try it online!

Mr. Xcoder

Posted 2017-10-17T11:53:55.173

Reputation: 39 774

3

Ohm v2, 3 bytes

#²Σ

Try it online!

Explanation

#    Range
 ²   Square
  Σ  Sum

Cinaski

Posted 2017-10-17T11:53:55.173

Reputation: 1 588

3

Japt, 3 bytes

ô²x

Try it here.

-1 thanks to Shaggy.

Explanation:

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

Erik the Outgolfer

Posted 2017-10-17T11:53:55.173

Reputation: 38 134

3 bytes using the shortcut for p2. – Shaggy – 2017-10-17T14:06:20.647

@FelipeNardiBatista fixed – Erik the Outgolfer – 2017-10-18T11:21:42.637

2

totallyhuman

Posted 2017-10-17T11:53:55.173

Reputation: 15 378

4#.#&@Range@#& saves a byte – miles – 2017-10-17T12:25:09.777

4#.#&@*Range . – alephalpha – 2017-10-17T13:42:11.053

2

Brain-Flak, 46 bytes

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

Try it online!

HyperNeutrino

Posted 2017-10-17T11:53:55.173

Reputation: 26 575

A little friendly competition :) – Riley – 2017-10-17T13:29:25.557

@Riley Ooh nice :) – HyperNeutrino – 2017-10-17T13:52:19.577

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)

– James – 2017-10-17T16:36:30.863

2

APL (Dyalog), 7 5 bytes

2 bytes saved thanks to @Mego

+.×⍨⍳

Try it online!

How?

- range

+.× - dot product

- with itself

Uriel

Posted 2017-10-17T11:53:55.173

Reputation: 11 708

@Uriel my bad, i thought the ¨⍳ was necessary – Felipe Nardi Batista – 2017-10-18T10:26:42.417

2

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

Luis Mendo

Posted 2017-10-17T11:53:55.173

Reputation: 87 464

How about ri),_.*:+ or ri),2f#:+? – Martin Ender – 2017-10-17T13:15:46.890

@Martin Good idea! I think you should post it as a different answer – Luis Mendo – 2017-10-17T13:25:02.137

2

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.

Uriel

Posted 2017-10-17T11:53:55.173

Reputation: 11 708

2

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

Mego

Posted 2017-10-17T11:53:55.173

Reputation: 32 998

2

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!

Cinaski

Posted 2017-10-17T11:53:55.173

Reputation: 1 588

2

R, 17 bytes

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

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

Frédéric

Posted 2017-10-17T11:53:55.173

Reputation: 2 059

1(x=0:scan())%*%x is shorter by a byte, but I believe you need a cat to get output. – Giuseppe – 2017-10-17T14:21:20.930

@Giuseppe I've just tried it and your code works without cat, it outputs a 1x1 matrix. – Rui Barradas – 2017-10-19T16:30:14.753

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

– Giuseppe – 2017-10-19T16:33:53.447

2

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#

Martin Ender

Posted 2017-10-17T11:53:55.173

Reputation: 184 808

2

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

Giuseppe

Posted 2017-10-17T11:53:55.173

Reputation: 21 077

2

><>, 15 13 11 bytes

Saved 2 bytes thanks to Not a tree

0:n:l1-:*+!

Try it online!

Outputs the sequence indefinitely.

Emigna

Posted 2017-10-17T11:53:55.173

Reputation: 50 798

1

14 bytes (12+2 for -v flag): ::1+:}+**6,n (Try it online!)

– Not a tree – 2017-10-18T01:43:30.557

1

Or 11 bytes (prints forever, starting at N=1): Try it online!

– Not a tree – 2017-10-18T02:00:53.233

@Notatree: Very nice idea using l. Checking with OP if it is okay to start at 1. – Emigna – 2017-10-18T06:28:49.650

@Notatree: Unfortunately we aren't allowed to start at 1, but it still saves 2 bytes. Thanks! – Emigna – 2017-10-18T09:52:08.053

1

(I should mention that I got the l idea from Martin Ender's Labyrinth answer.)

– Not a tree – 2017-10-18T14:59:52.283

2

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.

Martin Ender

Posted 2017-10-17T11:53:55.173

Reputation: 184 808

2

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

Dave

Posted 2017-10-17T11:53:55.173

Reputation: 432

Is there no square built in in Pyth? – caird coinheringaahing – 2017-10-17T15:54:32.673

Not as far as I know... – Dave – 2017-10-17T16:01:34.903

No there is no square built-in Pyth. Also 6 bytes

– Mr. Xcoder – 2017-10-17T16:15:48.060

15 bytes. – Steven H. – 2017-10-17T18:48:35.640

Fixable with +1 byte to each answer, I'll edit once I get off of mobile. – Dave – 2017-10-18T10:55:44.983

Five bytes solution works with versions of the Pyth compiler before this commit. It's just a bit harder to show off with an online compiler, seeing as all of those have gotten updated since mid-May.

– Steven H. – 2017-10-19T07:13:44.400

For an alternate five-bytes solution, s^R2h works. Numbers are turned into ranges with U automatically when mapped. – Steven H. – 2017-10-19T07:17:38.110

2

Haskell, 20 bytes

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

Try it online!

nimi

Posted 2017-10-17T11:53:55.173

Reputation: 34 639

2

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.

Martin Ender

Posted 2017-10-17T11:53:55.173

Reputation: 184 808

2

Excel, 19 bytes

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

Wernisch

Posted 2017-10-17T11:53:55.173

Reputation: 2 534

1

Oasis, 4 bytes

nk+0

Try it online!

Explanation

   0      # a(0) = 0
nk+       # a(n) = a(n-1)+n^2

Emigna

Posted 2017-10-17T11:53:55.173

Reputation: 50 798

1

Neim, 3 bytes

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

Try it online!

Okx

Posted 2017-10-17T11:53:55.173

Reputation: 15 025

1

Brachylog, 5 bytes

⟦^₂ᵐ+

Try it online!

Explanation

⟦        Range
 ^₂ᵐ     Map square
    +    Sum

Fatalize

Posted 2017-10-17T11:53:55.173

Reputation: 32 976

1

Gaia, 3 bytes

s¦Σ

Try it online!

Mr. Xcoder

Posted 2017-10-17T11:53:55.173

Reputation: 39 774

1

Perl 5, 24, 21 bytes

Thanks to Dom, solutions with 21 bytes

$\+=$_--**2while$_}{

or

map$\+=$_**2,1..$_}{

or

$\+=$_**2for 1..$_}{

previous were 21 + 1 -p flag, 3 bytes saved thanks to Xcali

$_*=($_+1)*(2*$_+1)/6

and 23 +1

$_=$_*($_+1)*(2*$_+1)/6

or

$_=$_**3/3+$_**2/2+$_/6

Nahuel Fouilleul

Posted 2017-10-17T11:53:55.173

Reputation: 5 582

You can shorten this by factoring out the $_ and replacing = with *=: Try it online!

– Xcali – 2017-10-17T15:44:00.183

This looks to be 22 bytes (21 + 1 for -p)... But here's one for 21 bytes using a different approach entirely: Try it online!

– Dom Hastings – 2017-10-18T10:13:47.170

1good point, there is also $\+=$_--**2while$_}{ – Nahuel Fouilleul – 2017-10-18T10:40:28.990

1

awk, 25 bytes

{print$1^3/3+$1^2/2+$1/6}

Nahuel Fouilleul

Posted 2017-10-17T11:53:55.173

Reputation: 5 582

1

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.

Conor O'Brien

Posted 2017-10-17T11:53:55.173

Reputation: 36 228

4%~3!2*>: saves a byte – miles – 2017-10-19T11:45:38.893

1

dc, 15 12 bytes

d1+dd+1-**6/

This is simply the factorised Faulhaber polynomial: n(n+1)(2n+1)/6, except that the (2n+1) term is calculated as 2(n+1)-1.

Toby Speight

Posted 2017-10-17T11:53:55.173

Reputation: 5 058

1

Funky, 33 24 19 bytes

-9 bytes thanks to Dennis

-5 bytes thanks to ASCII-only and bugfixes.

f=n=>n?f(n-1)+n*n:0

Try it online!

ATaco

Posted 2017-10-17T11:53:55.173

Reputation: 7 898

26 bytes – Dennis – 2017-10-19T05:53:13.143

1

Befunge, 28 bytes

&00pg#v_.@
-1:g00<^g00+*:p00

Works for inputs in the range [0, 128). Due to befunge being entirely stack-based, and yet having limited stack manipulation operations available, the only way to work with three values (sum, partial sum, and counter) is to store a value temporarily by modifying the program itself using the p instruction. Since p assigns a value as ASCII, the stored value wraps around at 128, storing a negative value instead of a positive value.

Try it online!

Befunge, 30 bytes

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

Works for pretty much any input.

Try it online!

Brian Gradin

Posted 2017-10-17T11:53:55.173

Reputation: 569

1

Python, 38 33 bytes

-5 bytes thanks to Martin Ender

g=lambda x:x*x+g(x-1) if x else 0


Haven't seen any solution with recursion yet, so I thought I'd post this one. It may not be really competitive, but this is my first time posting.

Edit: It would've been -11 bytes thanks to Martin Ender, but I would've ended up with the same answer as Mr. Xcoder's

pCozmic

Posted 2017-10-17T11:53:55.173

Reputation: 11

Welcome to PPCG! Here are a few ideas: x**2 is x*x, you can avoid the parentheses if you just put the condition on top and avoid the <1 if you switch the true and false branches (because 0 is falsy). However, y if x else 0 can be expressed more concisely as x and y, due to the short-circuiting behaviour of and. So you end up with g=lambda x:x and x*x+g(x-1). :) – Martin Ender – 2017-11-01T11:20:31.847

@Martin Ender Thank you for the tips. I am going to simplify the **2 and the <1, but I won't replace the ternary operator with the "and" statement, since it will be the same as Mr. Xcoder's second answer. – pCozmic – 2017-11-01T12:16:59.650

0

Proton, 16 bytes

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

Try it online!

Straightforward Solution: range+map(x=>x**2)+sum

-2 bytes thanks to Arnauld('s answer)

HyperNeutrino

Posted 2017-10-17T11:53:55.173

Reputation: 26 575

@FelipeNardiBatista Oh right, okay. Thanks. – HyperNeutrino – 2017-10-17T12:04:32.903

0

QBIC, 13 bytes

[:|p=p+a^2]?p

Explanation

[:|    FOR a = 1 to <input from cmd line>
p=p+   increment p by
a^2    a squared
]      NEXT
?p     PRINT p

steenbergh

Posted 2017-10-17T11:53:55.173

Reputation: 7 772

0

Java 8, 78 57 35 16 bytes

@Arnauld port

i->i*(i+++i)*i/6

Roberto Graham

Posted 2017-10-17T11:53:55.173

Reputation: 1 305

0

Pyke, 4 bytes

hLXs

Try it here!

or...

SMXs

Mr. Xcoder

Posted 2017-10-17T11:53:55.173

Reputation: 39 774

0

4, 39 bytes

3.7006110180020100000030301100001195034

Try it online!

How?

3.
7 00        grid[0] = input()
6 11 01     grid[11] = 1
8 00        while grid[0] != 0:
2 01 00 00     grid[1] = grid[0] * grid[0]
0 03 03 01     grid[3] = grid[3] + grid[1]
1 00 00 11     grid[0] = grid[0] - grid[11]
9         
5 03        print(grid[3]) 
4

Uriel

Posted 2017-10-17T11:53:55.173

Reputation: 11 708

0

Octave, 14 bytes

@(k)(a=0:k)*a'

Try it online!

*Dot product.

Or

@(k)sumsq(0:k)

Try it online!

rahnema1

Posted 2017-10-17T11:53:55.173

Reputation: 5 435

0

Haskell, 21 bytes

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

Try it online!

Boring, straightforward implementation of the closed-form formula on the OEIS page. Expanding into polynomial form doesn't save any bytes: f n=(2*n^3+3*n^2+n)/6.

Mego

Posted 2017-10-17T11:53:55.173

Reputation: 32 998

1Same byte count: f n=sum$map(^2)[1..n]. – Laikoni – 2017-10-17T13:37:29.697

0

Tcl, 36 bytes

proc S n {expr $n*($n+1)*(2*$n+1)/6}

Try it online!

sergiol

Posted 2017-10-17T11:53:55.173

Reputation: 3 055

Longer approach, that does not work well with zero: https://tio.run/##K0nO@f@/oCg/WSFYIU@hujwjMydVIUYFyMzMSy5SKFaITq0oKFJQydNSyYu1BovlKega1loXp5YoFNf@LygtAaoJVjCJ5YIxTWO5lGFsg9j/AA

– sergiol – 2017-10-17T13:20:16.327

Another longer approach, that does not work well with zero: https://tio.run/##K0nO@f@/oCg/WSFYIU@huiQzN1WhOjMvuUihWCE6taKgSCEazMuM1VLJjK1VUMmzLk4tUSiu/V9QWgJUEqxgEssFY5rGcinD2Aax/wE

– sergiol – 2017-10-17T13:21:08.243

Yet another longer approach, that does not work well with zero: https://tio.run/##K0nO@f@/oCg/WSFYIU@huiQzN1WhOrGgIDUvRaFYQTs6My@5SCEzVksls1ZBJc86taKgSEGluPZ/QWlJsUJ0sIJJLBeMaRrLpQxjG8T@BwA

– sergiol – 2017-10-17T13:35:36.293

The same approach as the Javascript answer has one byte more: https://tio.run/##K0nO@f@/oCg/WSFYIU@hOrWioEhBJU9LQyVPOzozL7lIIS9WU0slT9@s9n9BaUmxQnSwgkksF4xpGvsfAA Tks, @Arnauld

– sergiol – 2017-10-17T14:32:18.120

0

ARBLE, 14 13 bytes

-1 bytes thanks to Mr. Xcoder

n*~n*~(n+n)/6

Try it online!

ATaco

Posted 2017-10-17T11:53:55.173

Reputation: 7 898

13 bytes – Mr. Xcoder – 2017-10-17T16:20:17.667

0

Alice, 17 12 bytes

./ O \d2E+.

Try it online!

Prints the sequence indefinitely.

The trailing linefeed is significant.

Explanation

.   Duplicate the current total. Initially this pushes two zeros onto the
    previously empty stack.
/   Switch to Ordinal.
O   Print the current total with a trailing linefeed.
\   Switch back to Cardinal.
d   Push the stack depth, which acts as a counter variable.
2E  Square it.
+   Add it to the current total.
.   Duplicate it to increment the stack depth for the next iteration.

Martin Ender

Posted 2017-10-17T11:53:55.173

Reputation: 184 808

0

Ruby, 18 bytes

->n{n*~n*~(n+n)/6}

Using the sama formula as everybody else, saved 1 byte with a double negative multiplication.

Try it online!

G B

Posted 2017-10-17T11:53:55.173

Reputation: 11 099

0

Retina, 20 bytes

.+
$*
M!&`.+
1
$%_
1

Try it online!

Explanation

.+
$*

Convert input to unary.

M!&`.+

Get all overlapping matches of .+ which turns the input into a range of unary numbers from 1 to n.

1
$%_

Replace each 1 with the entire line its on, squaring the unary value on each line.

1

Count the number of 1s, summing all lines and converting them back to decimal.

Martin Ender

Posted 2017-10-17T11:53:55.173

Reputation: 184 808

0

Pari/GP, 16 bytes

n->(v=[0..n])*v~

Try it online!

alephalpha

Posted 2017-10-17T11:53:55.173

Reputation: 23 988

0

cQuents 0, 3 bytes

;$$

Try it online!

Take that, Oasis.

Explanation

;     Mode: Sum - given n, output the sum of the sequence up to n
 $$   Each term in the sequence equals the index * the index

Stephen

Posted 2017-10-17T11:53:55.173

Reputation: 12 293

does not work for input 0 – Felipe Nardi Batista – 2017-10-18T09:39:23.060

0

Recursiva, 8 bytes

smBa'Sa'

Try it online!

officialaimm

Posted 2017-10-17T11:53:55.173

Reputation: 2 739

0

Bash, 48 30 bytes

echo "$1*($1+1)*(2*$1+1)/6"|bc

Try it online!

0x45

Posted 2017-10-17T11:53:55.173

Reputation: 810

0

Pyth, 10 bytes

VhQ=+Z^N2Z

Outputs the first N elements of the sequence.

Try it online!


How?

VhQ=+Z^N2Z              Full program

VhQ                     Loop until Q + 1 is reached
   =+Z                  Assign and increment Z by ...
      ^N2               ... N squared
         Z              Implicity prints Z

11 byte alternative.

VhQ aY^N2sY

Try it online!

Ian H.

Posted 2017-10-17T11:53:55.173

Reputation: 2 431

0

Pushy, 6 bytes

R2KeS#

Try it online!

Explanation

R     Push integers from 1 to implicit n, where n is implicit input
2     Push 2
K     Next command will use the entire stack
e     Pop 2. Raise each of the remaing stack entries to that
S     Sum the entire stack
#     Print as integer

Luis Mendo

Posted 2017-10-17T11:53:55.173

Reputation: 87 464

0

Jq 1.5, 20 bytes

[range(.+1)|.*.]|add

Input is N. Output is N'th element of sequence. Expanded:

[
    range(.+1)            # generate series 0, 1, 2, 3, ... N
  | .*.                   # square each term
]                         # collect into an array
| add                     # compute the sum

Try it online!

jq170727

Posted 2017-10-17T11:53:55.173

Reputation: 411

0

K (oK), 9 bytes

Solution:

+/x*x:!1+

Try it online!

Examples:

> +/x*x:!1+4
30
> +/x*x:!1+5
55

Explanation:

Evaluated right-to-left:

+/x*x:!1+ / solution
       1+ / add 1 to input, 1+4 => 5
      !   / til, !5 => 0 1 2 3 4
    x:    / save as variable x
  x*      / vectorised multiplication, x*x, 0 1 2 3 4*0 1 2 3 4 => 0 1 3 9 16
+/        / addition over (sum), +/0 1 3 9 16 => 30

streetster

Posted 2017-10-17T11:53:55.173

Reputation: 3 635

0

C#(.NET Core), 20 bytes

a=>a*(a+1)*(2*a+1)/6

Try it online!

Probably

Posted 2017-10-17T11:53:55.173

Reputation: 207

0

R, 16 bytes

(n=0:scan())%*%n

Try it online!

Leaky Nun

Posted 2017-10-17T11:53:55.173

Reputation: 45 011

0

TacO, 10 bytes

@i i
+%+*i

Try it online!

ATaco

Posted 2017-10-17T11:53:55.173

Reputation: 7 898

0

Threead, 40 bytes

I[     -]_
   _^>1
  _2 _r

[<

 lo
 ]
+

Try it online!

De-sliced

This is actually 4 bytes larger, due to whitespace.

I[     -]_   lo
   _^>1   [< ]
  _2 _r     +

Process.

  1. Read an integer into the first value
  2. While the first value is non-zero.
    1. Blank the third value, push 2 onto it.
    2. Blank the second value, then calculate the first value to the power of the third, (i^2)
    3. Move the second value to the right and place a 1 onto it.
    4. Put the value of the first value onto the third value.
    5. Calculate the third value minus the second value (i-1)
  3. Now the second tape contains the squares of all numbers from inp to 1 squared.
  4. Blank the first value
  5. While the second value is non-zero
    1. Move the second tape to the left.
    2. Add the first value to the second value into the third value.
    3. Move the third value into the first value
  6. Now, all the i^2 values are summed together, output the first value.

ATaco

Posted 2017-10-17T11:53:55.173

Reputation: 7 898

0

ReRegex, 53 bytes

#import math
^k([1-9]\d*)/k($1-1)+$1*$1/k0+/0/k#input

Explained

#import math                # Import the math library.
^k([1-9]\d*)/k($1-1)+$1*$1/ # Search the buffer for "k" followed by a non-zero number. Replace it with "k<n-1>+n*n"
k0+/0/                      # Replace k0 with just 0
k#input                     # Default the buffer to k<input>

Try it online!

ATaco

Posted 2017-10-17T11:53:55.173

Reputation: 7 898

0

TI-BASIC, 10 bytes

sum(seq(X²,X,0,Ans

Quite simple. The sum of the sequence of the first Ans squares.

Khuldraeseth na'Barya

Posted 2017-10-17T11:53:55.173

Reputation: 2 608

0

MaybeLater, 36 bytes

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

Using the closed form formula.

Try it online!

ATaco

Posted 2017-10-17T11:53:55.173

Reputation: 7 898

Surely you could have posted two different approaches in the same answer? – Conor O'Brien – 2017-10-18T04:12:57.963

0

Common Lisp, 30 bytes

(loop as i to(read)sum(* i i))

Try it online!

Renzo

Posted 2017-10-17T11:53:55.173

Reputation: 2 260

0

JavaScript (ES6), 18 bytes

f=n=>n&&n*n--+f(n)

Try it

o.innerText=(
f=n=>n&&n*n--+f(n)
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
<input id=i type=number><pre id=o>

Shaggy

Posted 2017-10-17T11:53:55.173

Reputation: 24 623

0

TI-Basic, 10 bytes

sum(seq(OO,O,0,Ans

sp00ky

Timtech

Posted 2017-10-17T11:53:55.173

Reputation: 12 038

0

Milky Way, 10 bytes

'L§{:*}G!

Try it online!

Explanation:

'          push input to stack
 L         push inclusive range
  ${  }    map over every element ...
    :*     ... duplicate and multiply (square it)
       G   sum of list
        !  output

ovs

Posted 2017-10-17T11:53:55.173

Reputation: 21 408

0

Add++, 13 bytes

D,f,@,RdBcB*s

Try it online!

D,f,@,   - Create a monadic function called f. Argument n (example: 5)
      R  - Generate range;   STACK = [[1 2 3 4 5]]
      d  - Duplicate;        STACK = [[1 2 3 4 5] [1 2 3 4 5]]
      Bc - Push the columns; STACK = [[1 1] [2 2] [3 3] [4 4] [5 5]]
      B* - Product of each;  STACK = [1 4 9 16 25]
      s  - Push the sum;     STACK = [1 4 9 16 25 55]
         - Implicitly return 55

caird coinheringaahing

Posted 2017-10-17T11:53:55.173

Reputation: 13 702

0

Jelly, 3 bytes

Rḋ`

Try it online!

Mr. Xcoder

Posted 2017-10-17T11:53:55.173

Reputation: 39 774

-1

Postscript, 149 bytes

/d {def}def
/a {
0 i l 1 0 l
i 2 ge {/i i 1 sub d a}if
} d
/l {rlineto}d
/m {moveto}d
/b {/j exch d /i j d 0 0 m j a j 0 lineto closepath fill}d
5 b

MongoTheGeek

Posted 2017-10-17T11:53:55.173

Reputation: 101

-2

I'm a beginner in programming. I just do that for fun and I'm thankful for any help.

I tried in JavaScript:

var x = 9;

var y = 0;

var z;

for(var i=0; i<=x; i++){z = i*i; y += z;}

console.log(y)

Féileacán

Posted 2017-10-17T11:53:55.173

Reputation: 99

Input cannot be stored in a variable. It must be given by the user or taken as a function parameter. See this meta post

– mbomb007 – 2017-10-17T16:51:00.597

5Welcome to PPCG! The point of this challenge is to answer in as little code as possible. It looks like you've made a good start, but you can definitely make it shorter, such as by removing white space. In addition, please consider what @mbomb007 has said about taking input. – Giuseppe – 2017-10-17T16:51:52.600