[R] Return a vector in Fibonacci sequence function
arun
smartpink111 at yahoo.com
Fri May 10 16:29:23 CEST 2013
Hi,
May be this helps:
fibv =function(n)
{
f1 = f2 = 1
f3<- c(f1,f2)
for(i in seq(2, n-1)) {
if(n == 0 || n == 1) return(n)
if(n == 2) return(1)
f = f1 + f2
f2 = f1
f1 = f
f3<- c(f3,f)
}
f3
}
fibv(0)
#[1] 0
fibv(1)
#[1] 1
fibv(3)
#[1] 1 1 2
fibv(10)
# [1] 1 1 2 3 5 8 13 21 34 55
A.K.
>I've written the following piece of code, which returns the nth
Fibonacci number - how do i adapt it to return all the numbers in the
sequence up to n, >rather than a single value?
>
>fibv =
>function(n)
>{
>if(n == 0 || n == 1) return(n)
>if(n == 2) return(1)
>f1 = f2 = 1
>for(i in seq(2, n-1)) {
>f = f1 + f2
>f2 = f1
>f1 = f
>}
>f
>}
>fibv()
More information about the R-help
mailing list