Factorial with serial communication

I need help with the code for a factorial that calculates the factorial of a number selected in the serial port. I've got the code to work once however it only works once then goes off to display number like -36... ect. What's the cause of this, and possible solutions, or where to look?

What's the cause of this

You're joking, right?

(deleted)

Sorry I'm new here and wasn't sure what the go was, I probably should have added the code first off, however i figured out the problem was not returning the value of the unsigned long. Needed that push, apologies for a bad post.

Let me guess, it was just fine until (8!) right?

I hope you are not using a recursive algorithm. Bad juju with limited stack space.

Look at Sterling's Approximation when you overflow. You can see one implementation here

aarg: Let me guess, it was just fine until (8!) right?

No I have it working up until 13!

That's impressive - 13! requires more than 32 bits to represent. (try "usigned long long")

I hope you are not using a recursive algorithm. Bad juju with limited stack space.

Meh. A simple and bounded problem without much local data at each step. You'll probably exceed the range of a floating point number before you overflow the stack, even in an ATmega328. (about 34! ?) (and of course that's LONG after you overflow a 32bit integer.)