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 Aug 4 '17 at 19:52
• @Rod Sorry, you are right. I wrote 645321 instead of 654321. – Mr. Xcoder Aug 4 '17 at 19:54
• Can I take input as a list of digits? – totallyhuman Aug 4 '17 at 20:07
• @totallyhuman Yes, see the second spec. – Mr. Xcoder Aug 4 '17 at 20:08
• Interesting challenge. Glad you were inspired by mine! – Gryphon Aug 5 '17 at 23:09

sum.scanl1(+)

Try it online!

Takes input as list of digits. Calculates the cumulative sums then sums them.

Husk, 4̷ 2 bytes

Thanks @H.PWiz for -2 bytes!

Σ∫

Try it online!

"Ungolfed"/Explained

Σ    -- sum all
∫   -- prefix sums

Brain-Flak, 65, 50, 36 bytes

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

Try it online!

After lots of revising, I'm now very proud of this answer. I like the algorithm, and how nicely it can be expressed in brain-flak.

Most of the byte count comes from handling 0's in the input. In fact, if we could assume there were no 0's in the input, it would be a beautifully short 20-byte answer:

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

Try it online!

But unfortunately, brain-flak is notorious for bad handling of edge cases.

Explanation

First, an observation of mine:

If the input is n digits long, the first digit will appear in the triangle n times, the second digit will appear n-1 times, and so on onto the last digit, which will appear once. We can take advantage of this, since it's really easy to calculate how many digits of input are left in brain-flak, namely

[]

So here's how the code works.

# Push the size of the input (to account for 0's)
([])

# Push...
(

# While True
{

# Pop the stack height (evaluates to 0)
<{}>

# For each digit *D*...

# While true
{

# Decrement the counter (the current digit we're evaluating),
# but evaluate to 0
<({}[()])>

# Evaluate the number of digits left in the input
[]

# Endwhile
}

# This whole block evaluates to D * len(remaining_digits), but
# without affecting the stack

# Since we looped D times, D is now 0 and there is one less digit.
# Pop D (now 0)
{}

# Push the stack height (again, evaluating it as 0)
<([])>

# End while
}

# Pop a 0 off (handles edge case of 0)
{}

# end push
)

Pyth - 6 4 bytes

ss._

Nice 6 byte one that doesn't use prefix builtin:

s*V_Sl
• Nice! The best I could come up with is twice as long: s.e*bhk_ – Digital Trauma Aug 4 '17 at 21:10

MATL, 3 bytes

Yss

Try it online!

Takes the input as a list of digits.

Jelly, 3 bytes

+\S

Try it online! Uses the same technique as my Japt answer: cumulative addition, then sum.

• Oh, of course! :) – Jonathan Allan Aug 4 '17 at 20:25

Takes input as list of digits

f[]=0
f x=sum x+f(init x)

Try it online!

Takes input as string representation

f[]=0

Try it online!

Japt, 76 4 bytes

å+ x

Try it online!

Explanation

å+ x    Implicit: input = digit list
å+      Cumulative reduce by addition. Gives the sum of each prefix.
x    Sum.

Old solution:

å+ ¬¬x

Try it online!

Explanation

å+ ¬¬x   Implicit: input = string
å+       Cumulative reduce by concatenation. Gives the list of prefixes.
¬     Join into a single string of digits.
¬    Split back into digits.
x   Sum.
Implicit: output result of last expression
• Uh sandbox much? Or you read the question, wrote code and posted it all within one minute?! – Jonathan Allan Aug 4 '17 at 19:54
• @JonathanAllan This was not sandboxed. It is much easier than you might think. – Mr. Xcoder Aug 4 '17 at 19:55
• Uh, well I cant even read the question in the time it took – Jonathan Allan Aug 4 '17 at 19:55
• @JonathanAllan No sandbox reading, just happened to catch the question just after it was posted and come up with an algorithm almost immediately. – ETHproductions Aug 4 '17 at 19:58
• Welp it took me ~4min to read the question, so +1 for speed-reading/speed-understanding :) – Jonathan Allan Aug 4 '17 at 19:59

Brain-Flak, 28 bytes

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

Try it online!

14 bytes if we don't need to support zeros (which we do)

({({}<>{})<>})

Try it online!

DJMcMayhem has a cool answer here you should check out. Unfortunately for him I wasn't about to let him win at his own language :P

How does it work?

({({}<>{})<>})

The main action here is ({}<>{})<>, that takes the top of the left stack and adds to to the top of the right stack. By looping this operation we sum up the current stack (until it hits a zero) placing the sum on the off stack. That's pretty mundane, the interesting part is that we sum up the results of all these runs as our result. This will calculate the desired value. Why? Well lets take a look at an example, 123. On the first grab we just get 1 so our value is 1

1

On the next grab we return 1 plus the 2

1
1+2

On the last run we have all three together

1
1+2
1+2+3

Do you see the triangle? The sum of all the runs is the "triangle" of the list.

Ok but now we need it to work for zeros, here I used the same trick as DJMcMayhem, plus some fancy footwork. Instead of looping until we hit a zero we loop until the stack is empty.

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

I then used this tip, written by none other than yours truly, to golf off another 2 bytes.

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

And there we have it. I would be surprised if there was a shorter solution, but then again stranger things have happened.

• Unfortunately for him I wasn't about to let him win at his own language :P I expect nothing less from you. :D – DJMcMayhem Aug 5 '17 at 17:36

JavaScript (ES6), 28 bytes

a=>a.map(d=>t+=c+=d,t=c=0)|t

Takes input as a list of digits.

Python 3, 37 bytes

f=lambda n:len(n)and sum(n)+f(n[:-1])

Try it online!

• ...Why the downvote? – Business Cat Aug 4 '17 at 20:36
• I think you could change len to sum as well, though I don't believe that helps anything. – ETHproductions Aug 4 '17 at 20:39
• @ETHproductions Yeah. I was hoping I could make use of the fact that sum([]) is 0, but nothing was quite coming together... there might be a way though – Business Cat Aug 4 '17 at 20:41
• Didn't see this otherwise I'd have given you my improvement. – Jonathan Allan Aug 4 '17 at 20:57
• @JonathanAllan No worries :P – Business Cat Aug 4 '17 at 22:35

C# (.NET Core), 59 bytes

using System.Linq;N=>N.Reverse().Select((d,i)=>i*d+d).Sum()

Try it online!

Substantially different from the other C# answers. Input is a list of digits. All test cases included in the TIO link.

Could save a bunch of bytes if allowed to take input as a backwards list of digits with leading 0.

• Nice idea! Some fierce codegolfing in C#. – Grzegorz Puławski Aug 4 '17 at 20:55
• Nice solution! But isn't the input specified to be a non-negative number, not a list of digits? – Ian H. Aug 5 '17 at 7:03
• @IanH. Rule 2: You may take input and provide output by any allowed mean. When it comes to the format, you can take the input as an integer, as a String representation of the integer or as a list of digits. – Kamil Drakari Aug 5 '17 at 11:59

Python 3, 35 bytes

I just noticed that this is only really a slight golf of Business Cat's answer in the end though!

f=lambda a:a>[]and sum(a)+f(a[:-1])

Try it online!

• Funny that I ended up with a similar one only that it takes string and is longer.. :D – officialaimm Aug 5 '17 at 6:15

J, 7 bytes

[:+/+/\

Try it online! Takes a list of digits, such as f 6 5 4 3 2 1.

Explanation

[:+/+/\    (for explanation, input = 6 5 4 3 2 1)
\    over the prefixes of the input:
/         reduce:
this gives is the cumulative sum of the input:  6 11 15 18 20 21
[:         apply to the result:
+/           summation
this gives the desired result:   90

A little more true to the original problem would be [:+/@,]/, which is "sum" (+/) the flattened (,) prefixes of the input (]\).

Vim, 6059 32 keystrokes

Thanks a lot @CowsQuack for the tip with the recursive macro and the h trick, this saved me 27 bytes!

qqYpxh@qq@qVHJ:s/./&+/g⏎ C<C-r>=<C-r>"0⏎ Try it online! Ungolfed/Explained This will build the triangle like described (only that it keeps it left-aligned): qq q " record the macro q: Yp " duplicate the linex        "   remove last character
h       "   move to the left (this is solely that the recursive macro calls stop)
@q     "   run the macro recursively
@q  " run the macro

The buffer looks now like this:

53716
5371
537
53
5

Join all lines into one and build an evaluatable expression from it:

VH             " mark everything
J            " join into one line
:s/./&+/g⏎  " insert a + between all the characters

The " register now contains the following string (note missing 0):

5+3+7+1+6+ +5+3+7+1+ +5+3+7+ +5+3+ +5+ +

So all we need to do is append a zero and evaluate it:

C                " delete line and store in " register
<C-r>=       ⏎  " insert the evaluated expression from
<C-r>"    " register "
0   " append the missing 0

• You can use & (the whole match) instead of \1 in the substitute command – Kritixi Lithos Aug 7 '17 at 12:59
• qqYp$xq:exe"norm".col('.')."@q"⏎ can become qqYp$xh@qq@q. This recursive macro will encounter a breaking error when there is one character on the line, after which it will stop. – Kritixi Lithos Aug 7 '17 at 13:15
• So the substitution can just become :s/./&+/g. Also :%j⏎ can become V{J. And, Di can become C (I've already commented about this in another one of your Vim answers). Try it online! – Kritixi Lithos Aug 7 '17 at 13:21

Python 2, 49 45 bytes

-4 bytes thanks to Mr. Xcoder.

lambda n:sum(-~i*n[~i]for i in range(len(n)))

Try it online!

Takes input as a list of digits.

Bash + GNU utilities, 32 24

tac|nl -s*|paste -sd+|bc

Update: I see the input may be given as a list of digits. My input list is newline-delimited.

Explanation

tac                       # reverse digit list
|nl -s*                # prefix line numbers; separate with "*" operator
|paste -sd+     # join lines onto one line, separated with "+" operator
|bc  # arithmetically evaluate

APL, 4 bytes

+/+\

This takes the input as a list of digits, e.g.:

(+/+\) 5 3 7 1 6
66

Explanation

+/    sum of
+\  partial sums of input

Taxi, 1478 bytes

Try it online!

Un-golfed:

[ Pickup stdin and split into digits ]
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to Chop Suey.
Go to Chop Suey: north 1st right 1st left 4th right 1st left.
[a]
[ Count the digits ]
Switch to plan "b" if no one is waiting.
Pickup a passenger going to The Babelfishery.
Go to Zoom Zoom: north 1st left 3rd right.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 4th left 2nd right.
Pickup a passenger going to Addition Alley.
Go to Addition Alley: west 1st right 3rd right 1st right 1st right.
Pickup a passenger going to Addition Alley.
Go to The Babelfishery: north 1st right 1st right.
Go to Chop Suey: north 6th right 1st left.
Switch to plan "a".
[b]
Go to Addition Alley: north 1st left 2nd left.
Pickup a passenger going to Cyclone.
[c]
[ Multiply each digits by Len(stdin)-Position(digit) ]
Go to Zoom Zoom: north 1st left 1st right.
Go to Cyclone: west.
Pickup a passenger going to The Underground.
Pickup a passenger going to Multiplication Station.
Go to The Babelfishery: south 1st left 2nd right 1st right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: north 1st right 2nd left.
Pickup a passenger going to Addition Alley.
Go to The Underground: north 2nd left 1st right.
Switch to plan "d" if no one is waiting.
Pickup a passenger going to Cyclone.
Go to Addition Alley: north 3rd left 1st left.
Switch to plan "c".
[d]
Go to Addition Alley: north 3rd left 1st left.
[e]
[ Sum all the products ]
Pickup a passenger going to Addition Alley.
Go to Zoom Zoom: north 1st left 1st right.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to Addition Alley.
Switch to plan "f" if no one is waiting.
Switch to plan "e".
[f]
[ Output the results ]
Go to Zoom Zoom: north 1st left 1st right.
Go to Addition Alley: west 1st left 1st right.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: north 1st right 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.

Perl 5, 19 + 1 (-p) = 20 bytes

s/./$\+=$p+=$&/ge}{ Try it online! How?$\ holds the cumulative total, $p holds the total of the digits on the current line. Each line of the parallelogram is simply the previous line with the next digit of the number appended. Therefore, it is the sum of the previous line plus the new digit. This iterates over all of the digits, calculating the sums as it goes. The actual substitution is irrelevant; it's just a means to iterate over the digits without creating an actual loop. At the end,$\ is printed implicitly by the -p option.

Python 2, 56 bytes

lambda x:sum(i*int(x[-i])for i in range(1,1+len(x)))

Try it online!

• 54 bytes or 45 bytes with input as lists oft digits. – ovs Aug 4 '17 at 20:11

Jelly,  5  4 bytes

Ṛæ.J

A monadic link taking a list of decimal digits and returning the triangle of the number that list represents.

Try it online!

How?

Ṛæ.J - Link: list of numbers (the decimal digits), d   e.g. [9,4,5,0]
Ṛ    - reverse d                                            [0,5,4,9]
J - range(length(d))                                     [1,2,3,4]
æ.  - dot-product            (0*1 + 5*2 + 4*3 + 9*4 = 58)  58
• I had thought removing would still work. Pity... – ETHproductions Aug 4 '17 at 20:04
• @ETHproductions ...and yet there's a built-in to help! – Jonathan Allan Aug 4 '17 at 20:11
• ...okay, wow... – ETHproductions Aug 4 '17 at 20:14
• @ETHproductions ooops had to reverse it >_< – Jonathan Allan Aug 4 '17 at 20:19

Retina, 13 bytes

.
$`$&
.
\$*
1

Try it online! Link includes test cases. Explanation: The first stage generates all the prefixes of the original number, the second stage converts each digit to unary, and the third stage takes the total.

Mathematica, 49 bytes

Tr@Array[Tr@s[[;;#]]&,Length[s=IntegerDigits@#]]&
• You can take the input as a list of digits. #.Range[Length@#,1,-1]& – alephalpha Aug 5 '17 at 3:01
• Improving @alephalpha 's solution: #.Range[Tr[1^#],1,-1]& – JungHwan Min Aug 5 '17 at 3:06
• Tr@*Accumulate – alephalpha Aug 5 '17 at 12:10

Neim, 3 bytes

𝐗𝐂𝐬

Explanation:

𝐗        Get prefixes of input, including itself
𝐂       Implicitly join elements together, and create an array with all the digits
𝐬      Sum

Try it online!

𝐗𝐣𝐬

Explanation:

𝐗       Get prefixes of input, including itself
𝐣       Join
𝐬      Implicitly convert to a digit array, and sum

Try it online!

Java 8, 53 bytes

I implemented a lambda for each acceptable input type. They each iterate through the number's digits, adding the proper multiple of each to an accumulator.

Integer as input (53 bytes)

Lambda from Integer to Integer:

n->{int s=0,i=1;for(;n>0;n/=10)s+=n%10*i++;return s;}

String representation as input (72 bytes)

Lambda from String to Integer:

s->{int l=s.length(),n=0;for(int b:s.getBytes())n+=(b-48)*l--;return n;}

Digit array as input (54 bytes)

Lambda from int[] (of digits, largest place value first) to Integer:

a->{int l=a.length,s=0;for(int n:a)s+=n*l--;return s;}
• -7 bytes thanks to Olivier Grégoire
• a->{int l=a.length,s=0;for(int n:a)s+=n*l--;return s;} 54 bytes for the array version. – Olivier Grégoire Aug 23 '17 at 22:41

Pyt, 9 6 bytes

ąĐŁř↔·

Explanation:

Implicit input
ą                Convert to array of digits
Đ               Duplicate digit array
Łř↔           Create a new array [len(array),len(array)-1,...,1]
·          Dot product with digit array
Implicit output

Python 3, 94 58 54 bytes

Thanks to Mr. Xcoder for helping me save quite some bytes!

lambda n:sum(int(v)*(len(n)-i)for i,v in enumerate(n))

Try It Online!

Takes input as a string. It simply multiplies each digit by the number of times it needs to be added and returns their sum.

• Nice first answer, but please make your submission a serious contender by removing unnecessary whitespace, and making all variable / function names 1 byte long. 69 bytes – Mr. Xcoder Jan 21 '18 at 9:24
• – Mr. Xcoder Jan 21 '18 at 9:26
• @Mr.Xcoder Thanks. I will keep that in mind. – Manish Kundu Jan 21 '18 at 9:32
• You may not assume that it will always be called with 0. If p must always be 0, you should replace the p with p=0 in the lambda declaration. However, you can just remove p entirely to get 54 bytes – caird coinheringaahing Jan 21 '18 at 15:44

SNOBOL4 (CSNOBOL4), 79 bytes

N =INPUT
D	N LEN(1) . D REM . N	:F(O)
X =X + D
Y =Y + X	:(D)
O	OUTPUT =Y
END

Try it online!

Input from stdin, output to stdout.