5
\$\begingroup\$

I know that there may be better ways of writing this do you think that this code is written well enough to be used in a real world application?

    var pow = function ( base, power ) {
    var result = 1;
    if ( power < 0 ) {
        return ( 1 / pow( base, -(power)) );
    }
    for ( var i = 1; i <= power; i++ ) {
        result = result * base;
    }
    return result;
};
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Math.pow() - it's built in (and roughly 5 times faster) \$\endgroup\$ – Flambino Mar 28 '14 at 16:07
10
\$\begingroup\$

For a power function with an integer exponent you can loop through the bits in the exponent instead of making a linear loop:

function pow(base, power) {
    if (power < 0) return 1 / pow(base, -power);
    var b = base, result = 1;
    while (power > 0) {
        if ((power & 1) != 0) {
            result *= b;
        }
        power >>= 1;
        b *= b;
    }
    return result;
}

This will only loop as many times as there are bits used in the exponent, for a value like 1000 that means 10 iterations instead of 1000.

Testing this with pow(2, 1000) in Firefox shows that it is about 70 times faster (but the built in method is still even 8 times faster).

\$\endgroup\$
0
2
\$\begingroup\$

The code in the OP won't return a correct result for non-integer values of power: for example, 0.5 should return the square root of the number.

Sometimes you want to use the Floating Point Coprocessor for a calculation: instead of implementing an algorithm using software running on the CPU.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.