Even Fibonacci numbers

[This article was first published on Numbers around us - Medium, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Excel BI’s Excel Challenge #316 — solved in R

Defining the Puzzle:

Probably everyone of us have heard of Fibonacci Numbers. It is a sequence that property is that next number is a sum of two previous. But this time ExcelBI asked us to generate… first 20 even elements of this sequence.

Loading data:

Today we have only data to check if our sequence is exactly the same.

library(tidyverse)
library(readxl)

test = read_excel(“Even Fibonacci Numbers.xlsx”, range = “A1:A21”) %>% pull()

Approach:

As it looks pretty easy task and giving three approaches in different frameworks will change only small chunk of code. That there will be only one code today.

generate_even_fibonacci <- function() {
 fibonacci_sequence <- c(1, 2)
 even_fibonacci <- c(0, 2) 
 
 while (length(even_fibonacci) < 20) {
 next_fibonacci <- sum(tail(fibonacci_sequence, 2))
 fibonacci_sequence <- c(fibonacci_sequence, next_fibonacci)
 if (next_fibonacci %% 2 == 0) {
 even_fibonacci <- c(even_fibonacci, next_fibonacci)
 }
 }
 
 return(even_fibonacci)
}

even_fibonacci <- generate_even_fibonacci()

Validate result:

identical(even_fibonacci, test)
# > TRUE

If you like my publications or have your own ways to solve those puzzles in R, Python or whatever tool you choose, let me know.


Even Fibonacci numbers was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.

To leave a comment for the author, please follow the link and comment on their blog: Numbers around us - Medium.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)