自然数 [1、∞]の最初の k 項の和として f n
(k)各番号は n 回繰り返されます。
k | 0 1 2 3 4 5 6 7 8 9
--------+-------------------------------------------------
f_1(k) | 0 1 3 6 10 15 21 28 36 45
deltas | +1 +2 +3 +4 +5 +6 +7 +8 +9
--------+-------------------------------------------------
f_2(k) | 0 1 2 4 6 9 12 16 20 25
deltas | +1 +1 +2 +2 +3 +3 +4 +4 +5
--------+-------------------------------------------------
f_3(k) | 0 1 2 3 5 7 9 12 15 18
deltas | +1 +1 +1 +2 +2 +2 +3 +3 +3
この正方形配列の対角線は、 OEISシーケンスA134546 に似ています。
チャレンジ
2つの非負整数nとk をとり、 f n
(k)を出力するプログラム/関数 。
仕様
-
Standard I/O
rules apply. -
Standard
loopholes are forbidden. - Your solution can either be 0-indexed or 1-indexed for
n and/or k but please specify which. - This チャレンジ is not about finding the shortest approach in all
languages, rather, it is about finding the shortest
approach in each language. - Your code will be scored in bytes, usually in
the encoding UTF-8, unless specified otherwise. - Built-in functions that compute this sequence are
allowed but including a solution that doesn’t rely
on a built-in is encouraged. - Explanations, even for “practical” languages, are
encouraged.
テストケース
In these テストケース, n is 1-indexed and
k is 0-indexed.
n k fn(k)
1 2 3
2 11 36
11 14 17
14 21 28
21 24 27
24 31 38
31 0 0
いくつかのより良いフォーマットで:
1 2
2 11
11 14
14 21
21 24
24 31
31 0
1, 2
2, 11
11, 14
14, 21
21, 24
24, 31
31, 0
参照実装
これは、 Haskell で書かれています。
f n k = sum $ take k $ replicate n =<< [1..]
オンラインで試してみてください!
ベストアンサー
Ruby,
32 28 23 bytes
->n,k{k.step(0,-n).sum}
説明
合計を三角形の領域として視覚化してみましょう。たとえば、n = 3、k = 10などです。
*
*
*
**
**
**
***
***
***
****
最初の列は k
、次に k-n
、 k-2n
などとなります。