Good old factorial

A simple routine for computing the factorial in java, with good speed and low footprint.


static final double factorial(int n) {
    if (n < 0) {
        return Double.NaN;
    }
    if (n > 170) {
        return Double.POSITIVE_INFINITY;
    }
    double x = n, tail = x;
    switch (n & 7) {
    case 7: tail *= --x;
    case 6: tail *= --x;
    case 5: tail *= --x;
    case 4: tail *= --x;
    case 3: tail *= --x;
    case 2: tail *= --x;
    case 1: return FACT[n >> 3] * tail;
    case 0: return FACT[n >> 3];
    }
    return 0;//not reached
}

private static final double FACT[] = {
    1.0,
    40320.0,
    2.0922789888E13,
    6.204484017332394E23,
    2.631308369336935E35,
    8.159152832478977E47,
    1.2413915592536073E61,
    7.109985878048635E74,
    1.2688693218588417E89,
    6.1234458376886085E103,
    7.156945704626381E118,
    1.8548264225739844E134,
    9.916779348709496E149,
    1.0299016745145628E166,
    1.974506857221074E182,
    6.689502913449127E198,
    3.856204823625804E215,
    3.659042881952549E232,
    5.5502938327393044E249,
    1.3113358856834524E267,
    4.7147236359920616E284,
    2.5260757449731984E302,
};

Leave a Reply

two to the power eight 2^8