This isn't the solution I wanted to this problem, but it's pretty darn close, and it's easy to use.
What I have here is a header (.hpp) written in C++. It overloads the ! operator to allow factorials in your programs. This way, you don't have to write out the algorithm -- it's done for you and can be used almost as easily as the increment (++) operator.
For those who don't know, a factorial is the product of all integers leading up to that number. For example, 4! is 1 * 2 * 3 * 4, and 5! is 1 * 2 * 3 * 4 * 5.
The operator overload doesn't have a postfix in this case. I've created a class A that you can pass integers in. It is used like this:
!A()
where in the () is any legal integer or variable.
For example, to set x to factorial 5:
int x = !A(5);
To set something to the factorial of itself:
x = !A(x);
I apologize; I wasn't able to get something as tidy as "5!" as an expression. If anyone does, I'd appreciate it if they would share.
The actual working code is as follows:
class A
{
public:
A::A(int x): theVal(x) {}
int operator!();
private:
int theVal;
};
int A::operator!()
{
unsigned long int theFactorial = 1;
for(int i = 1; i <= theVal; i++)
{
theFactorial *= i;
}
return theFactorial;
}
That's it, really.
You then #include "factorial.hpp" into any .cpp file, and it's there for your coding purposes. All the syntax info is repeated in the .hpp file as a comment block, for easy access. A couple of notes also mentioned in the .cpp file:
Note that I use an
unsigned long int for the actual factorial work. Factorials add up very fast. !A(16) is the limit for this header; anything higher causes it to display the bit value equivalent, which isn't what you want (it appears as a very large negative number).
This limit
can be extended by changing all ints to doubles. However, then !A(10) and above gives answers similar to 12256+e26, and is therefore not desirable. (If you don't know why !A(17) is too much for a unsigned long, try it: 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 is a BIG number. How Calculator does it, I have no idea.)
Attached is the header file for C++, and a sample program that uses it, which I used to test my header. Enjoy.
[old attachment deleted by admin]