# Triangle a number!

We are used to the term "squaring" n to mean calculating n2. We are also used to the term "cubing" n to mean n3. That being said, why couldn't we also triangle a number?

# How to triangle a number?

• First off, let's pick a number, 53716.

• Position it in a parallelogram, whose side length equals the number of digits of the number, and has two sides positioned diagonally, as shown below.

    53716
53716
53716
53716
53716

• Now, we want to ∆ it, right? To do so, crop the sides that do not fit into a right-angled triangle:

    5
53
537
5371
53716

• Take the sums of each row, for this example resulting in [5, 8, 15, 16, 22]:

    5  -> 5
53  -> 8
537  -> 15
5371  -> 16
53716  -> 22

• Sum the list [5, 8, 15, 16, 22], resulting in 66. This is the triangle of this number!

# Specs & Rules

• The input will be a non-negative integer n (n ≥ 0, n ∈ Z).

• You may take input and provide output by any allowed mean.

• Input may be formatted as an integer, a string representation of the integer, or a list of digits.

• Default loopholes disallowed.

• This is , so the shortest code in bytes wins!

# More Test Cases

Input -> Output

0 -> 0
1 -> 1
12 -> 4
123 -> 10
999 -> 54
100000 -> 6
654321 -> 91


Inspiration. Explanations are encouraged!

• are you sure that 645321 -> 91 ?
– Rod
Commented Aug 4, 2017 at 19:52
• @Rod Sorry, you are right. I wrote 645321 instead of 654321. Commented Aug 4, 2017 at 19:54
• Can I take input as a list of digits? Commented Aug 4, 2017 at 20:07
• @totallyhuman Yes, see the second spec. Commented Aug 4, 2017 at 20:08
• Interesting challenge. Glad you were inspired by mine! Commented Aug 5, 2017 at 23:09

# Common Lisp, 53 52 bytes

(loop as(x . y)on(reverse(read))sum(+(reduce'+ y)x))


Input as list of digits.

Try it online!

-1 byte thanks to @ceilingcat.

• @ceilingcat, some Common Lisp compilers will actually fail when apply is applied against very long lists because of the call-arguments-limit. Commented Jan 31, 2018 at 10:00

# Perl 6, 13 bytes

Takes a list of digits

{[+] [\+] @_}


Try it online!

Perl 6 has a produce routine, which can be more tersely invoked using the 'triangle reduce' meta operator: [\ ]. Seems like it was made for this task.

# Vyxal, 2 bytes

¦∑


Try it Online!

### Explained

¦∑
¦  # cumulative sum
∑ # sum


## JavaScript (ES6), 34 bytes

f=(n,i=1)=>n&&n%10*i+f(n/10|0,i+1)


### Test cases

f=(n,i=1)=>n&&n%10*i+f(n/10|0,i+1)

console.log(f(0)) // -> 0
console.log(f(1)) // -> 1
console.log(f(12)) // -> 4
console.log(f(123)) // -> 10
console.log(f(999)) // -> 54
console.log(f(100000)) // -> 6
console.log(f(654321)) // -> 91

• Literally exactly what I had. However I do also have a 1-byte-shorter solution taking input as a string... Commented Aug 4, 2017 at 20:01
• @ETHproductions Ah, I first tried with a string but ended up with something longer. Commented Aug 4, 2017 at 20:06

# Gaia, 4 3 bytes

…_Σ


Function accepting a list of digits and leaving the result on the stack.

Try it online!

### Explanation

…    Prefixes
_   Flatten
Σ  Sum

• Crossed out 4 is still 4 :( Commented Aug 4, 2017 at 20:14
• What's the footer for?
– Okx
Commented Aug 7, 2017 at 12:30
• @Okx Each line in Gaia is a function (like Jelly), so the footer is just calling it. Commented Aug 7, 2017 at 15:34
• So, why doesn't it work without the footer?
– Okx
Commented Aug 7, 2017 at 15:44
• @Okx Because I haven't yet made it detect a list from the input format, so I have to eval it (e) first Commented Aug 7, 2017 at 15:47

# PowerShell, 5448 40 bytes

param($a)$a|%{$o+=$_*($a.count-$i++)};$o  Try it online! Takes input as a list of digits. Note that the output is just the input digit multiplied by its corresponding negative index in the string and then cumulatively summed. So, that's what we do here. We loop over each element in the input list, each iteration perform a multiplication, and then sum the results together into the total $o+=. That's left on the pipeline, output is implicit.

# C# (.NET Core), 80 bytes

n=>{int v=0,i=0;for(;i<n.Length;)v+=int.Parse(n[i]+"")*(n.Length-i++);return v;}


Try it online!

Takes a string as input and outputs the triangled number.

Explanation:

For each character in the input string, convert the char to an int and multiply it by the length of the string minus the index of the char.

# Python 3, 58 bytes

lambda n:sum(-~i*int(c)for i,c in enumerate(str(n)[::-1]))


Try it online!

# C# (.NET Core), 84 68 bytes

a=>a.Select((x,i)=>a.Take(i+1).Sum(c=>c-48)).Sum()


Byte count also includes

using System.Linq;


Try it online!

Explanation:

a=>                     // Take a string
a                   // Take the string as collection of chars
.Select((x,i)=>     // Replace the collection with
a.Take(i+1)     // Substrings increasing in size
.Sum(c=>c-48))  // Sum each substring's digits (as ints) together
.Sum()              // Sum the new collection of sums


I know it's a little bigger than there's already posted C# answer, but mine is coming from a different approach so I thought I will post it anyway.

# 05AB1E, 3 bytes

### Code

ηSO


Try it online!

### Explanation

η      # Take the prefixes of the number
S     # Split into single numbers
O    # Sum all the numbers


# PHP, 51 55 bytes

+4 bytes—original version failed on all inputs with 0 as a digit.

<?php while($x!=$d=array_pop($argv))$t+=++$p*$d;echo$t;  Try it online! EXPLANATION: <?php  The programme takes separate digits as CLI parameter arguments, which arrive in the code as an array, $argv.

Each character at a time is popped from the end of the array. When the array is empty array_pop returns null. Null is detected by comparing the result to an undeclared variable $x, a saving of 2 code bytes over using null itself. (Without this comparison any 0 digit evaluates to false and the loop ends early.) while ($x != $d = array_pop($argv))


$p is the position from the end i.e. the last digit (the first one popped) is in position 1. $p is undeclared and so equals 0, but is incremented before it is used each time, so starts off as 1.

The position is multiplied by the digit and added to the total $t. $t += ++$p *$d;


The final result is printed.

_(n/10)>n
2+6*!n>$o  # Excel VBA, 57 Bytes Anonymous VBE immediate window function that takes input from the range [A1], and outputs the triangle sum described above to the VBE immediate window l=[Len(A1)]:For i=1To l:s=s+Mid([A1],i,1)*(l+1-i):Next:?s  # Röda, 31 21 bytes {i=0{[i]if i+=_}|sum}  Try it online! Takes the input as a stream of digits. ## 31 bytes {addHead 0|reduceSteps _+_|sum}  Try it online! Takes the input as a stream of digits. Explanation: {addHead 0|reduceSteps _+_|sum} /* An anonymous function */ addHead 0 /* Append 0 to the beginning of the stream */ |reduceSteps _+_ /* Create a cumulative sum */ |sum /* Sum all numbers in the stream */  The reduceSteps function does not return the first item in the stream, so it is necessary to add a zero at the head of the stream. ## TXR Lisp, 67 40 bytes (opip digits reverse conses flatten sum)  Run: 1> (opip digits reverse conses flatten sum) #<intrinsic fun: 0 param + variadic> 2> [*1 53716] 66  Note that if we take advantage of the input being a list of integers representing digits, this reduces to: (opip reverse conses flatten sum)  and if the digits may be in reverse order already, then just (opip conses flatten sum)  Note also that this is a "useless use of opip"; all the terms are function names, and so [chain digits reverse conses flatten sum] could be used, and that would be the recommended way to code this; it's just one character longer. # Scala, 64 bytes def f(s:String)=s.indices.flatMap(i=>s.take(i+1).map(_-'0')).sum  # Python 3, 106 bytes a=input() c=[] d=0 b=[int(g) for g in a] for i in range(1,len(a)+1): c+=b[0:i] for t in c: d+=t print(d)  Try It Online! My original code was: a,c,d=input(),[],0 b=[int(g) for g in a] for i in range(1,len(a)+1): c+=b[0:i] for t in c: d+=t print(d)  But then I realized that by initializing all of my variables on one line, I gained two characters. :P • Ah Ah Ah! I am not the loser! Commented Apr 5, 2018 at 11:49 # R, 75 bytes function(x,b=nchar(x))sum(sapply(x%/%10^(0:b),function(y)y%/%10^(0:b)%%10))  Try it online! I did not see an R solution yet, so here goes.. • 49 bytes -- I had actually solved this but it was a snippet rather than a full program/function so yours is better. Commented Jan 24, 2018 at 16:54 • @Giuseppe 51 bytes: sum(cumsum(as.numeric(el(strsplit(scan(,""),""))))), but your version is 2 bytes shorter... Commented Apr 5, 2018 at 19:29 • @AndreïKostyrka we can join forces and get to 47 bytes! Commented Apr 5, 2018 at 19:39 # Ruby 29 bytes f=->n{*a,b=n;b ?n.sum+f[a]:0}  Try it online! # Add++, 11 6 bytes L~,¬+s  Try it online! # Fig, $$\2\log_{256}(96)\approx\$$ 1.646 bytes Sk  Try it online! Sk # Takes a list of digits as input k # Prefixes S # Sum of the automagically flattened list  # K (ngn/k), 10 8 bytes +/+\.'$:


Try it online!

-2 bytes thanks to ngn

Pretty basic train.

Explanation:

+/+\.'$: Main function. Takes implicit input with Right (:)$     Convert input to string
'      For each of the characters
.       Eval them, converting them into a number
+\        Cumulative sum
+/          Sum

• for converting to digits, .' works too
– ngn
Commented Oct 30, 2022 at 7:00

# Vyxal 3s, 1 byte

@


Try it Online!

yay

# Tcl, 97 bytes

proc T n {time {incr s [expr [regsub -all (.) $n +\\1]] regsub .$ $n "" n} [string len$n]
set s}


Try it online!

# Tcl, 105 bytes

proc T n {time {incr s [expr [join $L +]] set L [lreplace$L e e]} [llength [set L [split \$n ""]]]
set s}


Try it online!