how to write an optimized version of the following factorial recursion function in C along with some explanation please ??

int factorial(int num)
{
if (num == 0) return 1;
else return num * factorial(num - 1);
}

Looking forward for your help!

Thanks,
Nanda Kishor
http://www.c4swimmers.net

Recommended Answers

All 6 Replies

If you want it fast, don't use recursion.
If you want it faster still, create a local lookup table.

In addition to what Salem suggests, define optimized in your context.

Please try to explain in a bit detail about 'local lookup tables'.

It means having calculated the answer once, you store the result in a table.
Then if you need the same answer again, it's very quick to see what was stored previously.

Does it mean that there is a trade-off between memory & speed of execution?

Yes, that is a frequent choice you have to make.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.