# Sum the rows of the concatenated triangle

Consider the following triangle.

1
23
456
7891
01112
131415
1617181
92021222
324252627
2829303132
33343536373
839404142434
4454647484950
51525354555657
585960616263646
5666768697071727
37475767778798081


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.

# Rules

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

# Husk, 7 bytes

1-indexed

Σ!CNṁdN


Try it online!

### Explanation

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

1-indexed

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!

• n**2 is n*n. Sep 2 '17 at 13:07
• 69 bytes. Using Gauss' formula, sum(range(n)) = ~-n*n/2 = (n - 1) * n / 2 Sep 2 '17 at 13:12
• @Mr.Xcoder I think he does... Sep 2 '17 at 13:21
• @EriktheOutgolfer You're right, my bad 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

nLS¹L£θO


Try it online!

-1 thanks to Emigna.

1-indexing.

• You can remove your S if you replace J with S. Sep 4 '17 at 8:33
• @Emigna duh.... Sep 4 '17 at 8:35

{[~](1..$_²).substr(:1[^$_],$_).comb.sum}  Try it online! 1-indexed # Mathematica, 96 bytes (d=Flatten[IntegerDigits/@Range[#^2]];Last@Table[Tr@Take[d,{i(i+1)/2+1,(i+1)(i+2)/2}],{i,0,#}])&  Try it online! (in order to work on mathics "Tr" has to be replaced with "Total") # Jelly, 11 bytes ²RDFṁRS$ṫCS


Try it online!

Uses 1-based indexing.

## Explanation

²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
f=(1%(show=<<[1..])!!)


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
g=(rowSumSequence!!)

• n%x=sum[read[d]|d<-take n x]:(n+1)%drop n x is some bytes shorter. Sep 3 '17 at 15:08
• @Laikoni Thanks! Edited. I don't know why I thought the splitOn would save bytes. Sep 3 '17 at 17:36

# R, 11910910893 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 :)

• 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]. Sep 3 '17 at 18:20
• you can save 1 byte by changing as.integer with as.double Sep 4 '17 at 9:47
• Rather than x, use F as this is already initialised to 0. Sep 4 '17 at 11:05
• 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. Sep 4 '17 at 11:08
• 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. 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!

Explanation:

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.

🐖©a🚂➡🚂🍇


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

 🍮t🔤🔤


Assign an empty string to the variable t.

 🍮i 0


Assign i = 0.

 🔁▶l🐔t🍇


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

 🍎s


Return s

🍉


End method.

# PHP, 66+1 bytes

for($p=($n=$argn)*-~$n/2;$n--;)$r+=join(range(1,$p))[--$p];echo$r;  Run as pipe with -nR or try it online. requires PHP 5.4 or later for indexing the expression. # Pyth, 24 bytes u+GsH<>jkS+*QQ2/*QhQ2hQ0  Try it here: http://pyth.herokuapp.com/ # APL, 2826 25 bytes {+/⍎¨⍵↑⌽(+/⍳⍵)↑∊,/⍕¨⍳⍵×⍵}  Uses 1-based indexing Try it online! ## How? • ⍳⍵×⍵, 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 1-indexed (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! # Explanation (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;}  1-indexed -18 bytes thanks to @Nevay Explanation: 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  • 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;}. Sep 4 '17 at 14:27 # R, 99, 105, 97 bytes a=diag(N<-scan());a[upper.tri(a,T)]=strtoi(strsplit(paste(1:N^2,collapse=""),"")[[1]]);sum(a[,N])  1-indexed ungolfed version a <- diag(N<-scan()) a[upper.tri(a, diag=TRUE)] <- strtoi(strsplit(paste(1:N^2, collapse=""), "")[[1]]) sum(a[,N])  Try it here! thanks to @Giuseppe for saving 8 bytes • @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. Sep 4 '17 at 14:33 • See the linked "any standard mean" in the description :) Sep 4 '17 at 14:39 • @Giuseppe change and used your suggestion about strtoi Sep 4 '17 at 14:49 • 97 bytes, with a warning message. It's always good to include a link to TIO in your description so others can test it! Sep 4 '17 at 15:04 • @Giuseppe I don't know no R, but maybe a function would use less bytes? Sep 4 '17 at 15:08 # Perl 6, 44 bytes {[+] (1..*).flatmap(*.comb).rotor(1..*)[$_]}


Test it

## Expanded:

{
[+]        # 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 Ṭ€Ẏ0;œṗ²D€Ẏ$$⁸ịS  Try it online! 1-indexed. # SOGL V0.12, 15 13 bytes ²Δr∑.δ∑⌡kmčr∑  Try it Here! 1-indexed. While working on this I fixed a bug that made ∑ not work on number arrays and that m incorrectly took implicit input. Explanation: ² 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 #include<string> 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;}  • 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;} Sep 3 '17 at 17:58 • Also, if you're currently taking input as 0-indexed, you can convert it to 1-index and drop the ++n; Sep 3 '17 at 18:09 • @Zacharý Thanks. Btw, your code contains invisible unicode character for some reasons Sep 3 '17 at 18:24 • 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. Sep 3 '17 at 18:38 • @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 Sep 3 '17 at 18:47 # Pyth, 15 14 13 bytes s<>sMjkS^Q2sU  13 bytes alternatives: ssM<>jkS^Q2sU ssM<>jkS*QQsU s<>sMjkS^Q2sU  # How? 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\ @}})?/:0$\>$:@{{: :%a:/?(1:< ,a-]{+1[4 /~/ \+1~\ 1:<]{+1[+4@:-1\?( {1-}>{:}1(?\@1-@+ \0}~{{\\n; @:{{:<-1~$\!?)}}
~


1-Indexed

+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

$_=eval(substr((join'',1..$_*$_),($_**2-$_)/2,$_)=~s/./+\$&/gr)


Try it online!

Result is 1 indexed.

How?

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

f=
n=>eval([...(g=n=>n?g(n-1)+n:)(n*n).substr(n*~-n/2,n)].join+)
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

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

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