(KevinC's) Triangular DeciDigits Sequence
Mathematica, 42 bytes
#&@@RealDigits[1/#,10,#,-1].(#-Range@#+1)&
or
#&@@RealDigits[1/#,10,#,-1].Range[#,1,-1]&
or
Tr@Accumulate@#&@@RealDigits[1/#,10,#,-1]&
Explanation
Take the example from the challenge spec. We want to compute:
1+4+2+8+5+7+1
+ 1+4+2+8+5+7
+ 1+4+2+8+5
+ 1+4+2+8
+ 1+4+2
+ 1+4
+ 1
Rearranging, this is:
1*7 + 4*6 + 2*5 + 8*4 + 5*3 + 7*2 + 1*1
= (1, 4, 2, 8, 5, 7, 1) . (7, 6, 5, 4, 3, 2, 1)
where .
is the scalar product of two vectors.
That's pretty much all the solution does.
#&@@RealDigits[1/#,10,#,-1]
This gets us the first N
decimal digits of 1/N
(the #&@@
extracts the first element of the RealDigits
result because that also returns the offset of the first digit which we don't care about).
Then we get the list from N
down to 1
either using (#-Range@#+1)
or Range[#,1,-1]
, both of which are shorter than Reverse@Range@#
, and take the scalar product.
The alternative solution instead uses Accumulate
to compute a list of all prefix sums and then adds up those prefix sums with Tr
.
Since this is really fast even for large inputs, here is a scatter plot of the sequence up to N = 100,000
(doing all of them and plotting them took a while though):
Click for larger version.
The blue line is the naive upper bound of 9 N (N+1) / 2
(if all the decimal digits were 9
) and the orange line is exactly half of that. Unsurprisingly this is right inside the main branch of the plot since, statistically, we'd expect the average digit to be 4.5.
The thin line of plot points which you can see below the main branch are fractions which end in ...3333...
, as they all lie very close to 3 N (N+1) / 2
.
05AB1E, 12 11 bytes
Di<ë°¹÷.pSO
Try it online! or a Test suite for the first 50 numbers.
Explanation
# implicit input n
Di< # if n == 1 then 0
ë # else
°¹÷ # 10^n // n
.p # get prefixes
SO # sum digits
A more efficient version for trying big numbers on TIO
The difference to the shorter version is that here we sum the product of the digits and the reversal of their 1-based index instead of summing digits in prefixes.
Di<ë°¹÷SDgLR*O
Try it online!
Jelly, 9 bytes
R⁵*:%⁵+\S
Rather slow, but short. Try it online! or verify the first 50 test cases.
How it works
R⁵*:%⁵+\S Main link. Argument: n
R Range; yield [1, ..., n].
⁵* 10 power; yield [10**1, ..., 10**n].
: Divide each power by n.
%⁵ Take each quotient modulo 10.
This yields all desired decimal digits.
+\ Take the cumulative sum of the digits.
S Take the sum.