Fibonacci with n numbers instead of 2

5

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.

mroman

Posted 2018-11-25T20:19:51.183

Reputation: 1 382

Question was closed 2018-11-25T21:07:13.970

Can the function return more than 30 elements, or must it return exactly 30 elements? – Chas Brown – 2018-11-25T21:02:25.840

No, exactly 30. But it's a duplicate. Sorry about that. – mroman – 2018-11-25T21:12:19.080

Answers

2

JavaScript (ES6), 64 bytes

f=(n,i,a=[])=>i>29?a:f(n,-~i,[...a,(g=_=>n--&&a[--i]+g())()||1])

Try it online!

Arnauld

Posted 2018-11-25T20:19:51.183

Reputation: 111 334

1

05AB1E, 12 bytes

Å1 30FDO¸«ć,

Try it online!

Explanation

Å1            # push a list of n 1s
  30F         # 30 times do:
     D        # duplicate
      O       # sum
       ¸«     # append
         ć,   # extract and print the head

Emigna

Posted 2018-11-25T20:19:51.183

Reputation: 50 798

1

Tidy, 35 bytes

{x:30^recur(*tile(x,c(1)),sum@c,x)}

Try it online!

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

Conor O'Brien

Posted 2018-11-25T20:19:51.183

Reputation: 36 228

1

Python 2, 60 bytes

lambda n:reduce(lambda a,c:a+[sum(a[-n:])],'.'*(30-n),[1]*n)

Try it online!

Chas Brown

Posted 2018-11-25T20:19:51.183

Reputation: 8 959

1

Clean, 81 bytes

import StdEnv
$n=reverse(while((>)30o length)(\l=[sum(take n l):l])(repeatn n 1))

Try it online!

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

Οurous

Posted 2018-11-25T20:19:51.183

Reputation: 7 916