How fast does the program/algorithm run? (recursive vs iterative)
hi all,
I have a question and I don't understand how these things can be determineted..I have read many things about recursive and iterative solutions and most of them are says that it depends on your code your compiler,your computer etc.. but in exams,
instructor can ask "me how fast does the program/algorithm run?" how can i understand which one is faster ?? for example fibonacci algorithms or base calculating algorithms..i guess recursive is faster in mathematical programs like fibonacci ?? is that true ?? here above one simple code..please can you give me explanation which one is faster and why ???
thank you..
Quote:
Professors Reckless and Cautious are having an argument about C functions that they both claim print the hexadecimal representation of positive integers:
Code:
#define BASE 16
void Reckless(int val)
{
int digit;
if (val == 0)
{
/* do nothing */
}
else
{
Reckless(val / BASE);
digit = val % BASE;
if ((digit >= 0) && (digit <=9))
printf("%d", digit);
else
printf("%c", 55 + digit);
}
}
#define BASE 16
void Cautious(int val)
{
int remainder;
int highDigitValue, numDigits, digit;
int i;
highDigitValue = 1; numDigits = 0;
remainder = val;
while (remainder != 0)
{
remainder = remainder / BASE;
highDigitValue = highDigitValue * BASE;
numDigits++;
}
remainder = val;
highDigitValue = highDigitValue / BASE;
for (i=0; i<numDigits; i++)
{
digit = remainder / highDigitValue;
if ((digit >= 0) && (digit <=9))
printf("%d", digit);
else
printf("%c", 55 + digit);
remainder = remainder - digit * highDigitValue;
highDigitValue = highDigitValue / BASE;
}
}
Professor Cautious claims that his implementation is correct because his program first checks how many hexadecimal digits an integer values has and then prints these digits in the correct order. He further argues Professor Reckless’s implementation must be wrong because it does not count the number of hexadecimal digits. Professor Reckless, on the other hand, claims that there is no need to explicitly count the number of hexadecimal digits and therefore his recursive implementation is not only correct, but the program is much simpler and runs faster.