How to
Given an integer n
start with n
ones (i.e. 4 -> 1 1 1 1
). Then sum up the
last n
numbers, and repeat.
For n = 4
this looks like this:
Start with 1 1 1 1
, sum up the last 4 numbers resulting in 1 1 1 1 4
, then
sum up the last 4 numbers resulting in 1 1 1 1 4 7
, then sum up the last 4 numbers resulting in 1 1 1 1 4 7 13
and so on.
The task
Write a program or function that produces the first 30 numbers of this sequence given n
as input (either as argument, stdin, command line argument, on the stack, ...)
The 30 terms for n = 4 are:
1 1 1 1 4 7 13 25 49 94 181 349 673 1297 2500 4819 9289 17905 34513 66526 128233 247177 476449 918385 1770244 3412255 6577333 12678217 24438049 47105854
The 30 terms for n = 5 are:
1 1 1 1 1 5 9 17 33 65 129 253 497 977 1921 3777 7425 14597 28697 56417 110913 218049 428673 842749 1656801 3257185 6403457 12588865 24749057 48655365
In case n
is smaller than two or larger than 30 the behaviour can be undefined.
-
\$\begingroup\$ Can the function return more than 30 elements, or must it return exactly 30 elements? \$\endgroup\$Chas Brown– Chas Brown2018年11月25日 21:02:25 +00:00Commented Nov 25, 2018 at 21:02
-
\$\begingroup\$ No, exactly 30. But it's a duplicate. Sorry about that. \$\endgroup\$mroman– mroman2018年11月25日 21:12:19 +00:00Commented Nov 25, 2018 at 21:12
5 Answers 5
JavaScript (ES6), 64 bytes
f=(n,i,a=[])=>i>29?a:f(n,-~i,[...a,(g=_=>n--&&a[--i]+g())()||1])
05AB1E, 12 bytes
Å1 30FDO ̧«ć,
Explanation
Å1 # push a list of n 1s
30F # 30 times do:
D # duplicate
O # sum
̧« # append
ć, # extract and print the head
Tidy, 35 bytes
{x:30^recur(*tile(x,c(1)),sum@c,x)}
Explanation
{x:30^recur(*tile(x,c(1)),sum@c,x)}
{x: } lambda taking parameter `x`
30^ take the first 30 terms of...
recur( ) a recursive function
*tile(x,c(1)) whose seed is `x` `1`s
x with a window of `x`
sum@c and the functor takes the sum of its arguments
Clean, 81 bytes
import StdEnv
$n=reverse(while((>)30o length)(\l=[sum(take n l):l])(repeatn n 1))
(repeatn n 1)
gives us n
ones in a list, which we repeatedly prepend the sum of the first n
elements to (with (\l=[sum(take n l):l])
), while it has less than 30 elements.
As the list is backwards, we reverse it and return.