R function to find Fibonacci numbers
New to R, so apologies for any mistakes. I am making a R function to find 20 Fibonacci numbers starting from 1. I made this function, however the function outputs Fibonacci numbers like this:
# Output
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
I want this:
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
What troubles me is I don't want 2 'ones' at start. Only one "1" at start is required. Also, having trouble in function calling. Here is my code:
Ms <- function(moving_sum) {
Fib <- numeric(20)
Fib[1] <- Fib[2] <- 1
for (i in 3:20) Fib[i] <- Fib[i - 2] + Fib[i - 1]
return(Fib)
}
Ms(0)
Thanks.
--- Update ---
How to find the total count of even numbers? And the total sum of those even numbers?
Solution 1:
incorporate the following changes
Ms <- function(moving_sum) {
Fib <- numeric(moving_sum + 1) # Use the parameter moving_sum
Fib[1] <- Fib[2] <- 1
for (i in seq(3, moving_sum + 1)) Fib[i] <- Fib[i - 2] + Fib[i - 1]
return(Fib[-1]) # Remove the first number
}
Ms(20)
[1] 1 2 3 5 8 13 21 34 55 89 144 233 377
[14] 610 987 1597 2584 4181 6765 10946
Solution 2:
Try the code below
Ms <- function() {
Fib <- numeric(20)
Fib[1:2] <- 1:2
for (i in 3:20) Fib[i] <- Fib[i - 2] + Fib[i - 1]
evenFibs <- Fib[Fib %% 2 == 0]
list(
Fibs = Fib,
nrOfFibs = length(evenFibs),
sumEvenFibs = sum(evenFibs)
)
}
and you will get
> Ms()
$Fibs
[1] 1 2 3 5 8 13 21 34 55 89 144 233
[13] 377 610 987 1597 2584 4181 6765 10946
$nrOfFibs
[1] 7
$sumEvenFibs
[1] 14328