public int fibonacci(int n) {
if ((n == 0) || (n == 1)) // base cases
return n;
else
// recursion step
return fibonacci(n - 1) + fibonacci(n - 2);
}
Expected Run
fibonacci(0) → 0 0 OK
fibonacci(1) → 1 1 OK
fibonacci(2) → 1 1 OK
fibonacci(3) → 2 2 OK
fibonacci(4) → 3 3 OK
fibonacci(5) → 5 5 OK
fibonacci(6) → 8 8 OK
fibonacci(7) → 13 13 OK
other tests
OK
The difference equation for the Fibonacci series is:
u(n+2) = u(n+1) + u(n) with u(0) = 0, u(1) = 1
So:
u(n+2) - u(n+1) - u(n) = 0
Taking the z-transforms:
z^2[u(z) - u(0) - u(1)/z] - z[u(z) - u(0)] - u(z) = 0
u(z)[z^2 - z - 1] - z^2*u(0) - z*u(1) + z*u(0) = 0
Putting u(0) = 0 and u(1) = 1 this becomes:
u(z)[z^2 - z - 1] = z
z
u(z) = -------------
z^2 - z - 1
The denominator factorizes to:
[z-1/2 -sqrt(5)/2)][z-1/2 +sqrt(5)/2]
The trick here is to express u(z)/z in partial fractions:
1 1
u(z)/z = 1/sqrt(5)[ ---------------- - ---------------- ]
z-1/2 - sqrt(5)/2 z-1/2 +sqrt(5)/2
and so:
z z
u(z) = 1/sqrt(5)[---------------- - ------------------ ]
z-1/2-sqrt(5)/2) z-1/2+sqrt(5)/2
Then from table of inverse transforms:
z
------- = a^n
z - a
where a is constant. Then:
z z
u(z) = 1/sqrt(5) [-------------------- - --------------------]
z - (1/2+sqrt(5)/2) z - (1/2-sqrt(5)/2)
Now from the table of inverse transforms:
u(n) = 1/sqrt(5)[(1/2+sqrt(5)/2)^n - (1/2-sqrt(5)/2)^n]
u(n) = [(1/2+sqrt(5)/2)^n - (1/2-sqrt(5)/2)^n]/sqrt(5)
http://www.wolframalpha.copublic int fibonacci(int n) {
if ( n == 0 || n == 1) // base cases
return n;
else
// recursion step
return fibonacci(n - 1) + fibonacci(n - 2);
}
Title | # Comments | Views | Activity |
---|---|---|---|
advertisement module in core php | 4 | 81 | |
Controlled Assessment GCSE - desperate help needed | 4 | 48 | |
Where to store the queries for modification of table | 4 | 25 | |
github account with ecipse | 1 | 16 |
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
15 Experts available now in Live!