Consider the following triangle.


As you probably noticed, the first row is of length 1, and each row thereafter is 1 digit longer than to the previous one and that it contains the digits of the positive integers concatenated.

You will be given an integer N. Your task is to find the sum of the digits that lie on Nth row of the above triangle.


  • You can choose either 0 or 1 indexing. Please specify that in your answer.

  • Default Loopholes apply.

  • You can take input and provide output by any standard mean, and in any reasonable format.

  • This is OEIS A066548, and this sequence is the triangle itself (except that we do not remove leading zeros).

  • This is , so the shortest code in bytes (in every language) wins. Have fun golfing!

Test Cases

Input  |  Output

0  |  1
1  |  5
2  |  15
3  |  25
4  |  5
5  |  15
6  |  25
7  |  20
8  |  33
9  |  33
10 |  43
11 |  46
12 |  64

Note that the above are 0-indexed. If you are looking for 1-indexed test cases, increment the input by 1.

On a quite unrelated note, I recently changed my profile picture and that inspired me to write this challenge.


24 Answers 24


Husk, 7 bytes



Try it online!


    ṁ     Map then concatenate
     d    Integer digits
      N   Over the natural numbers
  CN      Cut into lists of lengths corresponding to the natural numbers
 !        Index it
Σ         Sum

Python 2, 69 bytes

This could probably be quite a bit shorter.


Edit: -7 bytes thanks to @Mr.Xcoder

lambda n:sum(map(int,"".join(map(str,range(1,n*n+1)))[~-n*n/2:][:n]))

Try it online!

  • 1
    \$\begingroup\$ n**2 is n*n. \$\endgroup\$ – Mr. Xcoder Sep 2 '17 at 13:07
  • \$\begingroup\$ 69 bytes. Using Gauss' formula, sum(range(n)) = ~-n*n/2 = (n - 1) * n / 2 \$\endgroup\$ – Mr. Xcoder Sep 2 '17 at 13:12
  • 1
    \$\begingroup\$ @Mr.Xcoder I think he does... \$\endgroup\$ – Erik the Outgolfer Sep 2 '17 at 13:21
  • \$\begingroup\$ @EriktheOutgolfer You're right, my bad \$\endgroup\$ – Mr. Xcoder Sep 2 '17 at 13:22

Haskell, 57 bytes

f n=sum[read[d]|d<-take n$drop(div(n*n-n)2)$show=<<[1..]]

Try it online!


05AB1E, 8 bytes


Try it online!

-1 thanks to Emigna.


  • \$\begingroup\$ You can remove your S if you replace J with S. \$\endgroup\$ – Emigna Sep 4 '17 at 8:33
  • \$\begingroup\$ @Emigna duh.... \$\endgroup\$ – Erik the Outgolfer Sep 4 '17 at 8:35

Perl 6, 47 45 42 bytes


Try it online!



Mathematica, 96 bytes


Try it online! (in order to work on mathics "Tr" has to be replaced with "Total")


Jelly, 11 bytes


Try it online!

Uses 1-based indexing.


²RDFṁRS$ṫCS  Input: n
²            Square
 R           Range, [1, n^2]
  D          Decimal digits
   F         Flatten
    ṁ        Reshape to
       $     Monadic chain
     R         Range, [1, n]
      S        Sum
        ṫ    Tail
         C   Complement, 1-n
          S  Sum

Haskell, 69 64 bytes

n%x=sum[read[d]|d<-take n x]:(n+1)%drop n x

Try it online.

Saved 5 bytes thanks to Laikoni!

Here's the less golfed version:

-- continuous stream of digits representing
-- the concatenation of positive integers in
-- order: 1234567891011...
digitstream = show=<<[1..]

-- sequence that yields the rows of the triangle
triangle n xs |(a,b)<-splitAt n xs=a:triangle(n+1)b

digitSum xs = sum[read[d]|d<-xs]

-- sequence that sums up the digits in each row
rowSumSequence = map digitSum (triangle 1 digitstream)

-- the final function that just shows the value 
-- at a given index
  • \$\begingroup\$ n%x=sum[read[d]|d<-take n x]:(n+1)%drop n x is some bytes shorter. \$\endgroup\$ – Laikoni Sep 3 '17 at 15:08
  • \$\begingroup\$ @Laikoni Thanks! Edited. I don't know why I thought the splitOn would save bytes. \$\endgroup\$ – Cristian Lupascu Sep 3 '17 at 17:36

R, 119 109 108 93 88 bytes

starting to golf.... 1-indexed

function(n){for(i in 1:n+n*(n-1)/2){F=F+strtoi(substr(paste(1:n^2,collapse=""),i,i))};F}

thanks @Zachary. your presumption is correct :) shaved 1 byte tnx to @Andrius and 15 more tnx to @user2390246

@Giuseppe - tnx for the strtoi. new to me. 5 bytes down :)

  • 2
    \$\begingroup\$ I don't think you need the y=, nor the parens around n*(n-1)/2+1, and the language's name presumably isn't [R]. \$\endgroup\$ – Zacharý Sep 3 '17 at 18:20
  • 1
    \$\begingroup\$ you can save 1 byte by changing as.integer with as.double \$\endgroup\$ – AndriusZ Sep 4 '17 at 9:47
  • 1
    \$\begingroup\$ Rather than x, use F as this is already initialised to 0. \$\endgroup\$ – user2390246 Sep 4 '17 at 11:05
  • 1
    \$\begingroup\$ Also, 1:n+a-1 gives the same as a:(a+n-1). In that case, you don't need to define a in advance, you can just put it straight in the for expression. That will also allow you to cancel out a +1/-1. \$\endgroup\$ – user2390246 Sep 4 '17 at 11:08
  • 2
    \$\begingroup\$ 79 bytes. Used substring instead of substr since really this is just a sum over the indices of the substring. Also, it's always good to include a TIO link for your solutions :) +1, great work. \$\endgroup\$ – Giuseppe Sep 4 '17 at 15:02

Emojicode, 182 bytes

🐖©a🚂➡🚂🍇🍦l➗✖a➕a 1 2🍮t🔤🔤🍮i 0🔁▶l🐔t🍇🍮➕i 1🍮t🍪t🔡i 10🍪🍉🍮s 0🔂g🔪t➖l a a🍇🍮➕s 🍺🚂🔡g 10🍉🍎s🍉

Defines a method called © that takes a 🚂 and returns a 🚂. 1-indexed.

Try it online!


Note: a lot of emoji choice doesn't make much sense in Emojicode 0.5. It's 0.x, after all. 0.6 will fix this, so if you want to learn this (because who wouldn't want to), I recommend waiting a moment.

Emojicode is an object-oriented programming language featuring generics, protocols, optionals and closures, but this program uses no closures, and all generics and protocols can be considered implicit.

The program operates on only a few types: 🚂 is the integer type and 🔡 is the string type. Additionally 👌s appear in conditions, which can take a value of either 👍 (true) or 👎 (false).

There are currently no operators in Emojicode, so addition, comparsions and other operations that are normally operators are implemented as functions, effectively making the expressions use prefix notation. Operators are also planned in 0.6.


© takes one 🚂 called a and returns a 🚂.

 🍦l➗✖a➕a 1 2

Declare a frozen ("constant") l equal to the a-th triangular number (formula in prefix notation). This represents the length of the string of numbers we need to generate.


Assign an empty string to the variable t.

 🍮i 0

Assign i = 0.


While the l is greater than the length of t

  🍮➕i 1

i += 1

  🍮t🍪t🔡i 10🍪

Append the textual representation of i in base 10 to t.


End loop

 🍮s 0

Assign s = 0

 🔂g🔪t➖l a a🍇

Take a substring of t starting at l - a (a - 1th triangular number) of length a, iterate over all characters

  🍮➕s 🍺🚂🔡g 10

Convert the character to string, parse integer in base-10, unwrap the optional (nothingness is returned if the string is not a number) and add to the s variable.


End loop


Return s


End method.


PHP, 66+1 bytes


Run as pipe with -nR or try it online.

requires PHP 5.4 or later for indexing the expression.


Pyth, 24 bytes


Try it here: http://pyth.herokuapp.com/


APL, 28 26 25 bytes


Uses 1-based indexing

Try it online!


  • ⍳⍵×⍵, 1 through the input squared
  • ⍕¨, turn each element into a string
  • ∊,/, concatenate them together
  • (+/⍳⍵)↑, grab the rows up to the input
  • ⍵↑⌽, grab the desired row
  • ⍎¨, turn each element into a number
  • +/, sum

Clojure v1.8, 154 bytes


(fn[n](loop[i 1 s(clojure.string/join""(take(* n n)(iterate inc 1)))](if(= i n)(apply +(map #(Character/digit % 10)(take n s)))(recur(inc i)(subs s i)))))

Try it online!


(take(* n n)(iterate inc 1))  Take the first N*N numbers
(clojure.string/join""...)    Combine them into a string
(loop[i 1 ...](if(= i n)...)  Loop N times
(apply +(map #(Character/digit % 10)(take n s)))  Take N characters from the string, convert to integers and add them
(recur(inc i)(subs s i))      Increment iterator, remove i characters from string

Java 8, 116 98 bytes

n->{String t="";int r=0,i=0;for(;i++<n*n;t+=i);for(i=0;i<n;r+=t.charAt(i+++~-n*n/2)-48);return r;}


-18 bytes thanks to @Nevay


Try it here.

n->{                             // Method with integer as both parameter and return-type
  String t="";                   //  Triangle-String
  int r=0,                       //  Result-integer
      i=0;                       //  Index-integer
  for(;i++<n*n;                  //  Loop (1) from 0 to `n^2` (exclusive)
    t+=i                         //   And append String `t` with all the numbers
  );                             //  End of loop (1)
  for(i=0;i<n;                   //  Loop (2) from 0 to `n` (exclusive)
    r+=t.charAt(i+++~-n*n/2)-48  //   And raise the sum `r` by the digits
  );                             //  End of loop (2)
  return r;                      //  Return the resulting sum of digits
}                                // End of method
  • 1
    \$\begingroup\$ 98 bytes: n->{String r="";int i=0,x=0;for(;x++<n*n;r+=x);for(x=0;x<n;)i+=r.charAt(x+++~-n*n/2)-48;return i;}. \$\endgroup\$ – Nevay Sep 4 '17 at 14:27

R, 99, 105, 97 bytes



ungolfed version

a <- diag(N<-scan())
a[upper.tri(a, diag=TRUE)] <- strtoi(strsplit(paste(1:N^2, 

Try it here!

thanks to @Giuseppe for saving 8 bytes

  • \$\begingroup\$ @Giuseppe in the description is mentioned: "You will be given an integer N." and this N is used in my solution. Or maybe I misunderstood something. \$\endgroup\$ – AndriusZ Sep 4 '17 at 14:33
  • \$\begingroup\$ See the linked "any standard mean" in the description :) \$\endgroup\$ – Giuseppe Sep 4 '17 at 14:39
  • \$\begingroup\$ @Giuseppe change and used your suggestion about strtoi \$\endgroup\$ – AndriusZ Sep 4 '17 at 14:49
  • 1
    \$\begingroup\$ 97 bytes, with a warning message. It's always good to include a link to TIO in your description so others can test it! \$\endgroup\$ – Giuseppe Sep 4 '17 at 15:04
  • \$\begingroup\$ @Giuseppe I don't know no R, but maybe a function would use less bytes? \$\endgroup\$ – NieDzejkob Sep 4 '17 at 15:08

Perl 6, 44 bytes

{[+] (1..*).flatmap(*.comb).rotor(1..*)[$_]}

Test it


  [+]        # reduce the result of the following using &infix«+»

  ( 1 .. * ) # infinite range starting at 1

  .flatmap(  # map, then flatten
    *.comb   # split into digits (100 ⇒ 1,0,0)

  .rotor(    # break the sequence into pieces
    1 .. *   # start with 1 value, then 2 values, then 3, etc.

  [$_]       # index into that infinite sequence

Jelly, 16 bytes


Try it online!



SOGL V0.12, 15 13 bytes


Try it Here!

While working on this I fixed a bug that made not work on number arrays and that m incorrectly took implicit input.


²              square the input
 Δ             get a range from 1 to that
  r∑           join as a string
    .δ         create a range 0 - input-1
      ∑        sum that
       ⌡       that many times do
        k        remove the 1st character of the joined string
         m     mold to the length of the input
          č    chop into characters
           r∑  convert to numbers and sum

C++, 180 bytes

-17 bytes thanks to Zacharý

Index start at 1

int s(int n){std::string t;int i=0,p=0;for(;i<=n;)p+=i++;for(i=0;t.size()<p;t+=std::to_string(++i));t=t.substr(0,p).substr(p-n);i=0;for(auto&a:t)i+=a-48;return i;}
  • \$\begingroup\$ Changing the last line to this should save two bytes: int s(int n){++n;std::string t;int i=0,p=0;for(;i<=n;)p+=i++;for(i=0;t.size()<p;t+=std::to_string(++i));t=t.substr(0,p);t=t.substr(t.size()-n);i=0;for(auto&a:t)i+=a-48;return i;} \$\endgroup\$ – Zacharý Sep 3 '17 at 17:58
  • \$\begingroup\$ Also, if you're currently taking input as 0-indexed, you can convert it to 1-index and drop the ++n; \$\endgroup\$ – Zacharý Sep 3 '17 at 18:09
  • \$\begingroup\$ @Zacharý Thanks. Btw, your code contains invisible unicode character for some reasons \$\endgroup\$ – HatsuPointerKun Sep 3 '17 at 18:24
  • \$\begingroup\$ Which one, my C++ suggestion, or my APL? APL uses its own codepage, and will probably not show up right if you do not have the right font. \$\endgroup\$ – Zacharý Sep 3 '17 at 18:38
  • \$\begingroup\$ @Zacharý The C++ suggestion you wrote in the comment. There's like 2 unicode characters before a zero, making errors like "0" identifier is unknown in visual studio. Same thing for to_string and size. You can see it if you copy-paste the code in notepad++, and convert encoding to ANSI, you will see some ?? in the editor \$\endgroup\$ – HatsuPointerKun Sep 3 '17 at 18:47

Pyth,  15 14  13 bytes


Try it here! or Check out the test suite.

13 bytes alternatives:



s<>sMjkS^Q2sU    Full program. Q means input.

       S^Q2      The range [1, Q^2].
     jk          Join as a String.
   sM            Convert each character to integer.
  >              All the elements of the above, but the first Q*(Q-1)/2.
 <               All the element of the above but the last Q.
s                Sum.
                 Output implicitly.

><>, 141+2 Bytes

::1+* 2,01\
:%a:/?(1:< ,a-]{+1[4
  /~/     \+1~\


+2b for -v flag

Tio.run really doesn't seem to like my ><> programs recently... It can still be verified on https://fishlanguage.com though. Input goes in 'initial stack'.

Edit: It turns out tio.run doesn't like it because it handles '[' and ']' differently to fishlanguage.com. fishlanguage.com reverses the stack when creating or removing a new stack, but tio.run doesn't.


Perl 5, 62 + 1 (-p) = 63 bytes


Try it online!

Result is 1 indexed.


Concatenate more than enough digits together, then skip the irrelevant ones at the beginning (length of skip is sum of integers from 1 to n-1). Take the next n digits, place a + in front of each one, then evaluate that equation.


JavaScript (ES6), 78 65 bytes

<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

1-indexed. Edit: Saved 13 bytes thanks to @tsh.

  • \$\begingroup\$ n=>eval([...(g=n=>n?g(n-1)+n:'')(n*n)].join<+>.substr(~-n*n-1,2*n)) \$\endgroup\$ – tsh Sep 7 '17 at 8:05
  • \$\begingroup\$ @tsh Still golfier to put the join`+` at the end... \$\endgroup\$ – Neil Sep 7 '17 at 8:14

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.