三角数


20

三角形号码是可以被表示为连续的正整数的总和,从1开始。它们也可以与式表示的数n(n + 1) / 2,其中n一些正整数。

数字的数字角对应项是通过以下方式计算的:

  1. 将数字拆分成一个数字数组,例如 613 => [6 1 3]
  2. 对于数组中的每个数字,计算n第三角形数;[6 1 3] => [21 1 6]
  3. 对结果数组求和; [21 1 6] => 28

给定一个整数n,您的任务是反复计算n的数字角对应物,直到结果等于1,然后输出所有计算出的值。您可以以任何顺序输出值,并且可以在数组的开头随意包含原始数字。这是一个因此最短的代码获胜。

测试用例

23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1

1
我们可以将原始数字作为结果数组的第一个吗?
Uriel's

1
我们怎么知道它总是下降到1?
Simply Beautiful Art

5
让我们假设一个数字大于141且有n数字。它的数字对角数可以具有的最大值是45n,所以digi-△(x) ≤ 45n < 45(1+log_10(x)),对于x > 141,我们有45(1+log_10(x)) < x,因此digi-△(x) ≤ x-1对于x > 141,一旦通过141限制,就可以通过程序进行蛮力证明。
Simply Beautiful

1
输出末尾可以加尾数1吗?
Simply Beautiful Art'17

1
相关:三角数,寻求其他证明该序列最终变为1。
Simply Beautiful Art

Answers:


10

外壳,6个字节

U¡(ṁΣd

在线尝试!

说明

U¡(ṁΣd
 ¡(       Iterate the following function on the input:
     d       Split the number into digits
   ṁΣ        Map each digit to its triangular number, then sum the results
U         Take the results of iteration until before the first repeated one

7

05AB1E6 5字节

Δ=SLO

在线尝试!编辑:由于@Emigna,节省了1个字节。说明:

Δ       Repeat until value doesn't change
 =      Print current value
  S     Split into characters
   L    Turn each character into range from 1 to N
    O   Sum

如果替换S,则可以跳过一个O
Emigna

@Emigna ...为什么L甚至表现那样?
尼尔

如果我没记错的话,那是一个错误,事实证明它是有用的,必须保留为一个功能。我认为这是向量化的第一种方法。
Emigna '17

4

J,20 19字节

(1#.2!1+,.&.":)^:a:

在线尝试!

也输出原始号码。

说明

(1#.2!1+,.&.":)^:a:
               ^:a:  Apply until input converges, storing all results in an array
(1#.2!1+,.&.":)      Digitangular sum
        ,.&.":         Split to digits
          &.":           Convert to string, apply left function, then undo conversion
        ,.               Ravel items (make array of singleton arrays of items)
                         This ensures that when cast back to integers, the digits are split.
      1+               Add 1 to each
    2!                 Compute (n choose 2) on each (nth triangular number)
 1#.                   Sum (debase 1)

1
[:+/-> 1#.喵!
FrownyFrog

@FrownyFrog不是一个原始的把戏,尽管我记得记得一定会充分利用它。
科尔

4

APL(Dyalog)23 20 17字节

@ngn节省了3个字节

{⍵∪⍨+/∊⍳¨⍎¨⍕⊃⍵}⍣≡

在线尝试!

怎么样?

⍵∪⍨ -将当前数组添加到

+/ -的总和

-扁平化

⍳¨ -每个范围

⍎¨⍕ -的位数

⊃⍵ -以前的值

⍣≡直到收敛。(union)的用法确保在连接第一个1之后,由于设置的唯一性,将排除下一个,并且数组将收敛。


出于好奇,如果不允许您也输出原始值又要多久?
caird coinheringaahing

@cairdcoinheringaahing 2个字节- 1↓(从头开始放置)
Uriel

@Uriel在这里,功率极限(⍣≡)比递归给出的解决方案更短:{⍵∪⍨+ / ∊⍳¨∊⍳¨⍎}⍣≡,但这很可惜APL没有一种简洁的方法来收集所有的迭代一个函数,直到收敛:⍵(f⍵)(f⍣2⊢⍵)(f⍣3⊢⍵)...
NGN

@ngn谢谢!我确实尝试使用幂运算符,但是我没有想到它在1之后会收敛的事实。将很快更新
Uriel

@ngn在{+/∊⍳¨⍎¨⍕⎕←⍵}⍣≡不打印最后1张的情况下如何使用的任何想法?
Uriel's

3

Haskell,51 47 46字节

f 1=[1]
f x=x:f(sum$do d<-show x;[1..read[d]])

在线尝试!

f 1=[1]                     -- if x == 1, return the singleton list [1]
f x=                        -- else
         do d<-show x       --  for each char 'd' in the string representation of x
                            --    (using the list monad)
           [1..read[d]]     --  make a list of [1..d]
                            --    (the list monad concatenates all those lists into a single list)
        sum                 --  sum those numbers
      f                     --  call f on it
    x:                      --  and put x in front of it 

编辑:@ H.PWiz保存了一个字节。谢谢!



2

Wolfram语言(Mathematica)43 41字节

Echo@#>1&&#0[#.(#+1)/2&@IntegerDigits@#]&

在线尝试!

怎么运行的

该表达式#.(#+1)/2&@IntegerDigits@#给出的数字角对应#。我们Echo进行输入,&&如果已经达到1,则使用短路评估来停止,否则将递归到手指对角。


-2个字节感谢Martin Ender的the .俩:Tr如果我们用#(#+1)/2点积代替乘法,则不必用数字求和#.(#+1)/2


2
现在才刚刚看到您的答案。您可以通过使用标量乘积技巧来避免我的TrEcho@#>1&&#0[#.(#+1)/2&@IntegerDigits@#]&
攻击,

@MartinEnder谢谢,这是一个巧妙的把戏。我想知道是否还有高尔夫球手方法可以“在固定点的途中打印此函数的所有迭代”(实质上是重新实现,FixedPointList除了两次打印固定点的方式外)。似乎应该已经出现了。
Misha Lavrov

2

Wolfram语言(Mathematica)49 42 39字节

感谢Misha Lavrov节省了3个字节。

#//.x_:>(y=IntegerDigits@Echo@x).++y/2&

在线尝试!++y由于某些原因,TIO需要在括号内加上括号。在我的本地Mathematica安装中,它可以在没有括号的情况下正常工作。)

在自己的行上打印每个值>>,并在其前面加上,并包括起始编号。


You can go back to beating my answer with #//.x_:>(y=IntegerDigits@Echo@x).++y/2&. (...maybe. For some reason, TIO doesn't like this, but Mathematica's fine with it?)
Misha Lavrov

Well, #//.x_:>(y=IntegerDigits@Echo@x).(++y)/2& is 41 bytes and works in TIO. But my copy of Mathematica doesn't think the parentheses are necessary.
Misha Lavrov

@MishaLavrov Thanks. Yeah, no clue why TIO needs the parentheses, but syntax in script files is sometimes a bit wonky.
Martin Ender

1

Ohm v2,  9  7 bytes

·Ω}#ΣΣu

Try it online!

Explanation

          Implicit input as a string
·Ω        Evaluate until the result has already been seen, pushing intermediate results
  }       Split digits
   #      Range from 0 to N
    ΣΣ    Sum
      u   Convert to string

Isn't u unnecessary?
Nick Clifford

It's necessary otherwise } won't split the digits
Cinaski

Hm. That might be a bug. I'll check it out.
Nick Clifford

1

Retina, 21 bytes

;{:G`
.
$*1¶
1
$%`1
1

Try it online! (The outputs of the individual cases aren't well separated, but each output ends with a 1.)

Prints each number on its own line, in order, including the starting number.

Explanation

;{:G`

This is just some configuration of the program. { makes the program loop until it fails to change the result (which happens once we get to 1), : prints number before each iteration, and ; prevents the final result from being printed twice at the end of the program. The G is just my usual way of creating a no-op stage.

.
$*1¶

Convert each digit to unary and put it on its own line.

1
$%`1

Compute the triangular number on each line, by replacing each 1 with its prefix. We could also use M!&`1+ here, which gives us all suffixes of each line.

1

Count all 1s, which sums up all the triangular numbers and converts the result back to decimal.


Is Retina a turing complete language?

@ThePirateBay yes.
Martin Ender

1

Ruby, 60 47 42 bytes

-13 bytes by @JustinMariner

-5 bytes by @GB

->x{p x=x.digits.sum{|k|k*-~k/2}while x>1}

Try it online!


You can drop the array and splat ([*...]) and change (k+1) to -~k to save a total of 5 bytes: Try it online! Additionally, you can save 8 more by switching to an anonymous lambda function: Try it online!
Justin Mariner

Hm, no idea why I thought .map couldn't take arrays.
Simply Beautiful Art

You can use "sum{...}" instead of "map{...}.sum" and then remove the space before "while"
G B

1

Befunge-93, 51 bytes

p&>>:25*%:1+*2/v
  |:/*52p00+g00<
00<vp000_@#-1.::g

Try it online!

James Holderness cleverly reshaped my progarm into a 51-byte form. Thanks!


1

Pushy, 24 22 21 17 bytes

[sL:R{;Svc^#&1=?i

Try it online!

Explanation

[sL:R{;Svc^#&1=?i

[           &1=?i   \ Loop until result == 1:
 s                  \   Split last result into digits
  L:  ;             \   For each digit n:
    R{              \       Push the range (1, n) inclusive
       S            \   Sum the ranges
        vc^         \   Delete all stack items, except the sum
           #        \   Print result


0

R, 70 bytes

f=function(n)"if"(n-1,c(n,f((d=n%/%10^(nchar(n):0)%%10)%*%(d+1)/2)),n)

Try it online!

Returns the original value as well.

R, 80 bytes

function(n){o={}
while(n-1){n=(d=n%/%10^(nchar(n):0)%%10)%*%(d+1)/2
o=c(o,n)}
o}

Try it online!

Does not return the original value.



0

05AB1E, 20 12 bytes

Saved 2 bytes thanks to caird coinheringaahing

ΔD,þ€iLO}O}}

Try it online!

Explanation

(old version)

Δþ€iD>*;}OD1›iD,}}1,  Main program
Δ                }    Repeat until there is no changes
 þ                    Push digits of the input number
  €i    }             Apply for each digit
    D>*;              Calculate the triangular number for given digit
         O            Sum all numbers
          D1›iD,}     Print if greater than 1
                  1,  Print 1 at the end

0

JavaScript, 61 57 bytes

f=a=>a-1?([...a+[]].map(b=>a+=b++*b/2,a=0),a)+' '+f(a):''

Try it online!



0

Charcoal, 18 bytes

W⊖Iθ«≔IΣ⭆θΣ…·0κθθ⸿

Try it online! Link is to verbose version of code. Explanation:

   θ                Input
  I                 Cast to integer
 ⊖                  Decrement
W   «               Loop while not zero
         θ          Current value
        ⭆           Map over characters and concatenate
             0      Literal character 0
              κ     Current character
           …·       Inclusive range
          Σ         Concatenate
       Σ            Sum of digits
      I             Cast to string
     ≔         θ    Assign back to value
                θ   Output latest value
                 ⸿  Move to start of next line


0

k, 19 bytes

{+/(+/1+!"I"$)'$x}\

Unsurprisingly works similarly to the already posted APL and J solutions

               $x    cast x (implicit var of lambda) to string
   (         )'      apply composition (function train) to each character of string
    +/1+!"I"$        cast character to number, create list from 1 to n, sum it
 +/                  sum triangular numbers
{                }\  iterate lambda until result converges, appending each result

0

Jelly, 7 bytes

DRFSµÐĿ

Try it online!

  • DRFSµÐĿ: Full program / monadic link.

  • ÐĿ: Loop until results are no longer unique (if something other than 1 would occur twice, then the given input does not have a defined result, since it would never reach 1).

  • D: Convert from integer to decimal.

  • R: Range (1-indexed). Vectorizes.

  • F: Flatten and S: Sum (µ just creates a new monadic chain)


0

dc, 31 bytes

[[I~d1+*2/rd0<m+]dsmxpd1<f]dsfx

The function m computes the digitangular function of its input; f repeats this until the result reaches 1.

Note that we use the input radix to extract digits - this means it will work in any base system, not only decimal.

Demo

for i in 23 72 55 78 613 8392 11111 8592025 999999999
    do echo $i '=>' $(dc -e $i'[[I~d1+*2/rd0<m+]dsmxpd1<f]dsfx')
done
23 => 9 45 25 18 37 34 16 22 6 21 4 10 1
72 => 31 7 28 39 51 16 22 6 21 4 10 1
55 => 30 6 21 4 10 1
78 => 64 31 7 28 39 51 16 22 6 21 4 10 1
613 => 28 39 51 16 22 6 21 4 10 1
8392 => 90 45 25 18 37 34 16 22 6 21 4 10 1
11111 => 5 15 16 22 6 21 4 10 1
8592025 => 117 30 6 21 4 10 1
999999999 => 405 25 18 37 34 16 22 6 21 4 10 1


0

Neim, 8 bytes

ͻ𝐂t𝕕𝐬D÷D

Explanation:

ͻ             Start infinite loop
 𝐂            Split top of stack into each of its characters
  t           Push infinite list of triangular numbers
   𝕕          For each of the characters, get the nth element in the above list.
    𝐬          Sum.
     D         Duplicate.
      ÷        If top of stack is equal to 1, break.
       D       Duplicate.
               Implicitly print all elements in the stack, concatenated.

Try it online!

Formatted output


0

D, 140 bytes

import std.algorithm,std.range,std.conv,std.stdio;void f(T)(T n){n=n.text.map!(u=>u.to!T-48+(u.to!T-48).iota.sum).sum;n.writeln;if(n-1)n.f;}

Try it online!


0

PHP, 71+1 bytes

for(;1<$n="$s"?:$argn;print$s._)for($i=$s=0;$p--||~$p=$n[$i++];)$s+=$p;

Run as pipe with -nR or try it online. (requires PHP 5.3 or later for the Elvis operator)


What's the Elvis operator?
caird coinheringaahing

@cairdcoinheringaahing A?:B: if A is truthy then A else B
Titus

0

Add++, 32 bytes

D,f,@,EDBFEREss
+?
y:1
W!,$f>x,O

Try it online!

Doesn't output the first value

How it works

D,f,@,   - Create a monadic function, f.
         - Example argument: [613]
      ED - Digits;   STACK = [[6 1 3]]
      BF - Flatten;  STACK = [6 1 3]
      ER - Range;    STACK = [[1 2 3 4 5 6] [1] [1 2 3]]
      Es - Sum each; STACK = [21 1 6]
      s  - Sum;      STACK = [28]

           f calculates n's digitangular counterpart

+?       - Take input;     x = 613; y = 0
y:1      - Set y to 1;     x = 613; y = 1
W!,      - While x != y...
   $f>x, -   Call f;       x =  28; y = 1
   O     -   Print x;

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.