| x is considered arbitrary and only multiplications are permitted.
For example, x^98 is computed by the following 8 multiplies:
operation comment
--------- -------
y1=x*x x^2
y2=y1*y1 x^4
y3=y2*y2 x^8
y4=y3*y3 x^16
y5=y4*y4 x^32
y6=y5*y5 x^64
y7=y6*y5 x^96
y8=y7*y1 x^98
y8 is the desired result.
I don't believe shifts are relevant to the question posed.
This algorithm is important to compilers that wish to generate
in-line code for computing small integer powers of integer variables.
The algorithm used above (for exponent 98) is the binary multiplicative
algorithm. This is not always the most efficient algorithm (as is
mistakenly believed by some). I am asking for an example that shows
that this algorithm is not always best.
It would be interesting to see if our compilers do this right.
I took a look at the VAX-11 FORTRAN compiler, but found that it
called OTS$POWJJ to do the exponentiation.
|
|
Using the notation of the previous examples:
Operation Comment
--------- -------
y1=x*x x^2
y2=y1*y1 x^4
y3=x*y2 x^5
y4=y3*y3 x^10
y5=y3*y4 x^15
But 15 = 1111 which would yield 6 multiplies.
2
One way of stating a more general algorithm is that whenever the exponent
is factorable we may "nest" the applications of the algorithm; i.e. by
computing x^(ab) as ((x^a)^b) or ((x^b)^a), whichever is better. It is
pretty obvious that if one of the factors is a power of two this reduction
accomplishes nothing, but 3 yields good results....
|
| The smallest power for which the binary method fails is 15.
"The factor method is based on a factorization of n. If n = p*q, wgere p is
the smallest prime factor of n, and q > 1, we may calculate x^n by first
calculating x^p and then raising this quantity to the qth power. If n is
prime, we may calculate x^(n-1) and multiply by x. And, of course, if n = 1,
we have x^n with no calculation at all. Repeated applications of these rules
gives a procedure for evaluating x^n, for any given n."
"The factor method is better than the binary method on the average, but there
are cases (n = 33 is the smallest example) where the binary method excels."
from "The Art of Computer Programming", Donald E. Knuth, Vol.2, p.401
The text continues (for about 18 pages) with more powerful methods of reducing
the number of multiplications required to evaluate powers.
- Gilbert
P.S. Eight multiplications are required for x^98.
|