Reputation:
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.
How to find the total count of even numbers? And the total sum of those even numbers?
Upvotes: 0
Views: 956
Reputation: 111
# You need to define first few cases only, and then it's simple
fibonacci <- function(n) {
if (n <= 0) return(numeric(0))
if (n == 1) return(0)
if (n == 2) return(c(0, 1))
fib <- numeric(n)
fib[1] <- 0
fib[2] <- 1
for (i in 3:n) {
fib[i] <- fib[i-1] + fib[i-2]
}
return(fib)
}
Upvotes: 0
Reputation: 101753
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
Upvotes: 0
Reputation: 79238
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
Upvotes: 1