S
Sathyaish
Can every problem that has an iterative solution also be expressed in
terms of a recursive solution?
I tried one example, and am in the process of trying out more examples,
increasing their complexity as I go. Here's a simple one I tried out:
#include<stdio.h>
/* To compare the the time and space cost of iteration against
recursion*/
const int SOME_CONST = 10;
void ifoo();
void rfoo(int, int, int);
int main(void)
{
ifoo();
rfoo(0, 0, 5);
printf("\n");
return 0;
}
void ifoo()
{
int i = 0, x = 0, y = 5;
for(; i < SOME_CONST; i++)
{
x += y;
printf("%d\t%d\t%d\t\n", i, x, y);
}
}
void rfoo(int i, int x, int y)
{
x += y;
printf("\n%d\t%d\t%d", i, x, y);
if (i < SOME_CONST - 1)
rfoo(++i, x, y);
}
I noted the following:
a. While iteration is linear in time and constant in space, recursion
is exponential in space.
b. Iteration preserves state, recursion does not.
terms of a recursive solution?
I tried one example, and am in the process of trying out more examples,
increasing their complexity as I go. Here's a simple one I tried out:
#include<stdio.h>
/* To compare the the time and space cost of iteration against
recursion*/
const int SOME_CONST = 10;
void ifoo();
void rfoo(int, int, int);
int main(void)
{
ifoo();
rfoo(0, 0, 5);
printf("\n");
return 0;
}
void ifoo()
{
int i = 0, x = 0, y = 5;
for(; i < SOME_CONST; i++)
{
x += y;
printf("%d\t%d\t%d\t\n", i, x, y);
}
}
void rfoo(int i, int x, int y)
{
x += y;
printf("\n%d\t%d\t%d", i, x, y);
if (i < SOME_CONST - 1)
rfoo(++i, x, y);
}
I noted the following:
a. While iteration is linear in time and constant in space, recursion
is exponential in space.
b. Iteration preserves state, recursion does not.