How to check whether a vector is a Fibonacci sequence of numbers

Viewed 144

Background: Fibonacci numbers are a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. A simple example is: 1, 1, 2, 3, 5, 8, etc.

I am trying to understand how can I detect whether a vector contains Fibonacci numbers or not. Is it possible to accomplish this through a vectorized operation (I mean without using a loop)?

1 Answers

After the first element, the differences between elements in a Fibonacci sequence should be the sequence. So, an easy solution is

F1 = c(2,5,7,12,19,31)
F2 = c(2,5,7,12,18,31)

all(diff(F1)[-1]  == head(F1, -2))
[1] TRUE
all(diff(F2)[-1]  == head(F2, -2))
[1] FALSE
Related