|
From: St0fF 6. <st...@gm...> - 2001-11-13 12:24:17
|
HI!
Recursive functions normally need a lot more time -> wanna speed it up -
ITERATE (do it in one for() / while() construct using only ONE FUNCTION
CALL).
maybe I'll get it right:
int fibonacci_iterated(int max) {
if (max<0) {return 0;}
else {/*register*/ int n=0, m=1,o=1;
for(int i=0;i<=max;i++) {
m+=n; n=o; o=m;}
return o;}
}
I mean, if you use C then use it right! I know some functions are very easy
coded recursively,
but this implies a lot of stacking and jumping around, and therefore it
needs a lot of extra - calling - time. So if a recursive function should
get speeded up, you have to count upwards instead of downwards. You need to
iterate instead of recursing (, and btw. you need more variables ...).
Hope this helps,
St0fF.
----- Original Message -----
From: "Williams, Timothy W." <TIM...@sa...>
To: "'Mansoor Nathani'" <man...@sy...>; "Dev users"
<dev...@li...>
Sent: Friday, November 09, 2001 10:11 PM
Subject: RE: [Dev-C++] Efficiency
> #include <iostream.h>
> #include <stdlib.h>
> int fib(int z);
> int fib_iter(int a, int b, int count);
>
> void main(void)
> {
> int n;
> cout << "Enter n:\n";
> cin >> n;
> cout << "My Way...\n";
> cout << fib_iter(1, 0, n);
> cout << "\n and now your way...\n";
> cout << fib(n);
>
> }
>
>
> int fib_iter(int a, int b, int count)
> {
> if (count == 0)
> return 1;
> else
> return a+fib_iter(a+b, a, count-1);
>
> }
> int fib(int z)
> {
> if (z==-1)
> return 1;
> if (z==-2)
> return 0;
> else
> return (fib(z-1)+fib(z-2));
> }
>
>
> > -----Original Message-----
> > From: Mansoor Nathani [mailto:man...@sy...]
> > Sent: Friday, November 09, 2001 3:46 PM
> > To: Dev users
> > Subject: [Dev-C++] Efficiency
> >
> >
> > Can any one please show me how to increase the efficiency of this
> > recursive program?
> >
> > THe program is supposed to output the fibonacci sequence up to a given
> > value.
> >
> > I need it to output in the middle of the recursive function, but
> > a lot of garbage gets acumulated.
> >
> > Any help would be appreciated.
> >
> > Thanks
> >
> > Mansoor
> >
> >
> > #include <iostream.h>
> > int fib(int z);
> >
> > void main(void)
> > {
> > int c;
> > for (int abc=0;abc<10;abc++)
> > cout<<fib(abc)<<endl;
> > cin>>c;
> > }
> >
> > int fib(int z)
> > {
> > if (z==-1)
> > return 1;
> > if (z==-2)
> > return 0;
> > else
> > return (fib(z-1)+fib(z-2));
> > }
> >
> > _______________________________________________
> > Dev-cpp-users mailing list
> > Dev...@li...
> > https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
> >
>
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
|