vonjd - 6 months ago 43

R Question

Fibonacci n-step number sequences is a generalization of Fibonacci numbers where you add more than two of the preceding numbers together. I try to write a function in R that does that.

First the classical Fibonacci numbers:

`fib <- function(n){`

fib <- vector()

fib[1] <- 1

fib[2] <- 1

for(i in 3:n){

fib[i] <- fib[i-1] + fib[i-2]

}

return(fib)

}

fib(7)

## [1] 1 1 2 3 5 8 13

Next the so called Tribonacci numbers:

`fib3 <- function(n){`

fib <- vector()

fib[1] <- 1

fib[2] <- 1

fib[3] <- 2

for(i in 4:n){

fib[i] <- fib[i-1] + fib[i-2] + fib[i-3]

}

return(fib)

}

fib3(7)

## [1] 1 1 2 4 7 13 24

and so on...

The initial values are powers of 2, so for n=3 it is 1,1,2, for n=4 it is 1,1,2,4, for n=5 it is 1,1,2,4,8 and so on.

So my idea is to modify the above function on the fly, especially the number of arguments in the for-loop, yet I don't know enough of R to achieve that efficiently.

How can I modify the above code to create any Fibonacci n-step number sequence?

Many more details and different implementations can be found here... unfortunately not in R: Rosetta code Fibonacci n-step number sequences

Answer

If the user supplies `n`

(the step-number) and `starting`

, a vector of exactly `n`

starting values, and `K`

, the desired number of elements in the sequence, you could do something like the following.

```
n <- 7
K <- 100
starting <- c(1,1,1,1,1,1,1)
fibn <- function(n, K, starting){
sequence <- vector(mode='numeric', length=K)
sequence[1:n] <- starting
for(i in (n+1):K){
sequence[i] <- sum(sequence[(i-n):(i-1)])
}
return(sequence)
}
```