28
\$\begingroup\$

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!

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

60 Answers 60

2
\$\begingroup\$

Pari/GP, 20 bytes

Takes the input as a list of digits.

a->a*Colrev([1..#a])

Try it online!


Pari/GP, 17 bytes

Takes the input as a polynomial. For example, 5*x^4 + 3*x^3 + 7*x^2 + x + 6 means 53716.

a->x=1;eval(a+a')

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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

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

Gaia, 4 3 bytes

…_Σ

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

Try it online!

Explanation

…    Prefixes
 _   Flatten
  Σ  Sum
\$\endgroup\$
  • 1
    \$\begingroup\$ Crossed out 4 is still 4 :( \$\endgroup\$ – Mr. Xcoder Aug 4 '17 at 20:14
  • \$\begingroup\$ What's the footer for? \$\endgroup\$ – Okx Aug 7 '17 at 12:30
  • \$\begingroup\$ @Okx Each line in Gaia is a function (like Jelly), so the footer is just calling it. \$\endgroup\$ – Business Cat Aug 7 '17 at 15:34
  • \$\begingroup\$ So, why doesn't it work without the footer? \$\endgroup\$ – Okx Aug 7 '17 at 15:44
  • \$\begingroup\$ @Okx Because I haven't yet made it detect a list from the input format, so I have to eval it (e) first \$\endgroup\$ – Business Cat Aug 7 '17 at 15:47
1
\$\begingroup\$

PowerShell, 54 48 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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Python 3, 58 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

echo $t;
\$\endgroup\$
1
\$\begingroup\$

Python 2, 46 bytes

  • Takes in string, returns integer
f=lambda a:a and sum(map(int,a))+f(a[:-1])or 0

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Ruby, 32 bytes

->a{b=a.pop;a[0]?b+a.sum+f[a]:b}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Python 2, 56 bytes

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

Try it online!

Some edit as suggested by @Mr.Xcoder

Python 2, 50 bytes

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

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ 50 bytes (-6 bytes). (i+1) means bitwise -~i, thus requiring no brackets and -i-1 is just ~i, again bitwise. range(0,len(a)) is equivalent to the unary range range(len(a)). \$\endgroup\$ – Mr. Xcoder Aug 5 '17 at 20:29
1
\$\begingroup\$

Excel VBA Immediate Window, 60 bytes

a=StrReverse([A1]):For i=1 ToLen(a):b=b+i*Mid(a,i,1):Next:?b

Input is in cell A1 of the active sheet. Output is to the VBA immediate window.

\$\endgroup\$
1
\$\begingroup\$

Clojure, 26 bytes

#(apply +(reductions + %))

There's a built-in, but in standard Clojure fashion, it's a long-ass word. Takes input as a list of digits.

\$\endgroup\$
  • \$\begingroup\$ Can you add a testing link or instructions on how to run it? \$\endgroup\$ – Mr. Xcoder Aug 7 '17 at 15:40
1
\$\begingroup\$

TI-BASIC, 4 bytes

sum(cumSum(Ans

Takes a list of digits as input, and calculates the sum of the cumulative sum (i.e. prefix sum) of the list.

The cumSum( token is 2 bytes large.

\$\endgroup\$
1
\$\begingroup\$

Math++, 56 bytes

?>n
n>g
o+g%10>o
_(g/10)>g
3+3*!g>$
_(n/10)>n
2+6*!n>$
o
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Scala, 64 bytes

def f(s:String)=s.indices.flatMap(i=>s.take(i+1).map(_-'0')).sum
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ Ah Ah Ah! I am not the loser! \$\endgroup\$ – sergiol Apr 5 '18 at 11:49
1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 49 bytes -- I had actually solved this but it was a snippet rather than a full program/function so yours is better. \$\endgroup\$ – Giuseppe Jan 24 '18 at 16:54
  • \$\begingroup\$ @Giuseppe 51 bytes: sum(cumsum(as.numeric(el(strsplit(scan(,""),""))))), but your version is 2 bytes shorter... \$\endgroup\$ – Andreï Kostyrka Apr 5 '18 at 19:29
  • 1
    \$\begingroup\$ @AndreïKostyrka we can join forces and get to 47 bytes! \$\endgroup\$ – Giuseppe Apr 5 '18 at 19:39
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

Add++, 11 6 bytes

L~,¬+s

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Ruby 29 bytes

f=->n{*a,b=n;b ?n.sum+f[a]:0}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

Gol><>, 8 bytes

IEh@+:@+

Try it online!

Input format is space-separated digits.

How it works

IEh@+:@+

I         Take next input as number
 E        If last input was EOF...
  h       Print the top as number and halt
          Otherwise...
          The stack looks like [sum_of_digits triangle digit]
   @      Move 3rd from top (sum_of_digits) to the top
    +     Add top two (update `sum_of_digits`)
     :    Duplicate top
      @+  Add `sum_of_digits` to `triangle`
          Repeat from the beginning
\$\endgroup\$
0
\$\begingroup\$

C (gcc), 51 50 bytes

-1 byte thanks to @ceilingcat

i,r;f(t,l)int*t;{for(;l;)for(i=--l;~i;)r+=t[i--];}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

EXCEL, 55 bytes

Using Immediate Window.

[A65:A89]="=MID(REPT(CHAR(ROW())&CHAR(ROW()+1),2),1,3)"
\$\endgroup\$
0
\$\begingroup\$

Zsh, 60 bytes

f(){echo $((${(j:+:)${(@f)$(for i in $@;echo $((x+=i)))}}))}

Try it online!

Takes input as individual parameters

\$\endgroup\$

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.