factorial.cpp

Submitted by reeses on Sat, 2005-03-26 22:02. |

This is a quick hack that was the result of a discussion on interview questions. A friend's coworker asked an interview candidate,"Can you write a recursive factorial function?" My friend and I joked about hazing an interviewer or an interviewee in the situation -- what language, what's the maximum value to expect, should we eliminate tail calls, etc. So, taking something that would be easy in lisp ((defun fact (x) (cond ((= x 0) 1) (t (* x (fact (1- x)))))), untested ), I wrote a quick and lazy char*-based solution in C. All I did was implement simplistic decrement, addition, and multiplication mechanisms for strings of numbers. It was interesting to see four lines of lisp turn into 140 lines of sloppy C.
As a caveat, this runs beautifully on MSVC/Win2k, but acts strangely on Linux. It also leaks memory like a sieve, because I don't free() anything. I do not think the two problems are coincidental. Tant pis.

Post new comment

Captcha Image: you will need to recognize the text in it.
Please type in the letters/numbers that are shown in the image above.