c++ - Efficient way to compute p^q (exponentiation), where q is an integer -
what efficient way compute pq, q integer?
exponentiation squaring uses o(lg q) multiplications.
template <typename t> t expt(t p, unsigned q) { t r(1); while (q != 0) { if (q % 2 == 1) { // q odd r *= p; q--; } p *= p; q /= 2; } return r; } this should work on monoid (t, operator*) t constructed 1 identity element. includes numeric types.
extending signed q easy: divide 1 result of above absolute value of q (but usual, careful when computing absolute value).
Comments
Post a Comment