1.

Solve : Re: Operator overload -- Factorials (C++)?

Answer»

Quote from: Dilbert on March 30, 2007, 04:30:40 PM

Code: [Select]typedef UNSIGNED long int ULONG;
class A
{
public:
    A::A(int x): theVal(x) {}
    ULONG operator!();
private:
    ULONG theVal;
};

ULONG A::operator!()
{
    ULONG theFactorial = 1;
    for(int i = 1; i <= theVal; i++)
    {
        theFactorial *= i;
    }
    return theFactorial;
}
Code: [Select]#include <iostream&GT;
#include "factorial.hpp"
using std::cout;
using std::cin;
using std::endl;

//NOTE: !A(variable || number) is factorial, NOT the "not" modifier.
int main()
{
    cout << "Enter an integer: " << endl;
    ULONG input;
    cin >> input;
    ULONG x = !A(input);
    cout << input << " factorial is " << x << endl;
    return 0;
}
This is the original program, revamped. It has all integers re-done as ULONG, which is typedef'd as unsigned long int. The program accepts up to 33! before RETURNING 0.

However, I still like the macro better; it's smaller and easier to read. Too bad it can't be made PERFECT. Oh well.
one could write a biginteger implementation that implements multiplication and get almost limitless factorials...

Or of course you could simply use the support for bigInteger's built into Java or .NET.


Discussion

No Comment Found