Algorithm: calculate x^p

You can calculate x^p by multiplying x p times: x*x*x*x....x*x. The "cost" will be n multiplications.

I know it is possible to create a more effective algorithm, with the "cost" log n, by using divide and conquer, and the fact that x^p = x^(p/2)*x^(p/2)^...

Thankful for your help,

Danne

[312 byte] By [dannenya] at [2007-11-26 19:40:36]
# 1
What's your question?
jverda at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 2
I wonder how that more effective algorithm can be written. I have been thinking of this to much, had to let it out :)
dannenya at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 3
What have you tried? What specific difficulty are you encountering?
jverda at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 4
I have an idea of that x^(n/2)^2 needs only half of calculations compared to x^(n/2)... But how can i write it in pseudocode?
dannenya at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 5
The pseudocode is trivial:pow (x:Number, n:Integer) => pow(x, n/2)*pow(x, n - n/2)
pm_kirkhama at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 6

> ... calculate x^p by multiplying x p times:

> x*x*x*x....x*x. The "cost" will be n multiplications.

> ... using divide and

> conquer, and the fact that x^p = x^(p/2)*x^(p/2)^...

>

> ... how can i write it in pseudocode?

Imagine x to the power of 19.

Break down 19 to binary: 10011, read this from lsb.

Result starts as 1.

Intermediate value starts as x.

Repeat

.Multiply intermediate value into result if the current bit of the exponent is 1.

.Square intermediate value.

When you run out of digits in the exponent, you have the result.

tschodta at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 7
Yes, more efficient algorithms exist. Some are discussed in Knuth: The Art of Computer Programming Volume 2 chapter 4.6.3.
jsalonena at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...
# 8
> Yes, more efficient algorithms exist. Some are> discussed in Knuth: The Art of Computer> Programming Volume 2 chapter 4.6.3.That is a nice arithmetical trick. And, amazingly, already invented in 1427 (according Knuth)!
prometheuzza at 2007-7-9 22:20:51 > top of Java-index,Other Topics,Algorithms...