I don't know C# but I have heard it is very simillar to Java. I am giving the Java code
int Fibonacci(int n)
{
int low=0, hi=1;
for(int i=1;i%26lt;n;i++)
{
int tempHi=hi;
hi=low+hi;
low=tempHi;
}
return hi;
}
}
Using recursion is not good. because recursive version is of order O(n^2) and has too much function call overhead.
While iterative version( my one) is O(n) that is linear time.
C# code in fibonacci method?
ALGORITHM 1A: BINARY RECURSION
#include %26lt;stdio.h%26gt; /* Required to use printf() */
/* Function f(n) returns the n'th Fibonacci number
* It uses ALGORITHM 1A: BINARY RECURSION
*/
unsigned int f(int n) {
return n%26lt;2 ? 1 : f(n-1)+f(n-2);
}
/* Function f_print(n) prints the n'th Fibonacci number */
void f_print(int n) {
printf("%dth Fibonacci number is %lu\n",n,f(n));
}
/* Function main() is the program entry point in C */
int main(void) {
f_print(46);
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment